Java Strings

Java Strings Course – Key String Methods in Action

Strings are widely used in Java. In this course, we will demonstrate essential Java String methods in one practical program, which includes length()charAt()substring()equals()toUpperCase(), and replace(). You’ll get a good sense of how these methods work together in a real-world scenario.

public class StringMethodsDemo {
    public static void main(String[] args) {
        String str = "  Hello, Java World!  ";

        // 1. length() - Get the length of the string
        System.out.println("Length of string: " + str.length()); // Output: 22

        // 2. charAt() - Get character at a specific index
        System.out.println("Character at index 7: " + str.charAt(7)); // Output: J

        // 3. substring() - Extract a part of the string
        System.out.println("Substring (7 to 11): " + str.substring(7, 11)); // Output: Java

        // 4. equals() - Compare two strings for equality
        String str2 = "Hello, Java World!";
        System.out.println("Are the strings equal? " + str.equals(str2)); // Output: true

        // 5. toUpperCase() - Convert string to uppercase
        System.out.println("Uppercase: " + str.toUpperCase()); // Output: "  HELLO, JAVA WORLD!  "

        // 6. replace() - Replace part of the string
        System.out.println("Replaced string: " + str.replace("Java", "Programming")); // Output: "  Hello, Programming World!  "

        // 7. trim() - Remove leading and trailing spaces
        System.out.println("Trimmed string: " + str.trim()); // Output: "Hello, Java World!"
    }
}

Program Explanation:

  1. length() – Prints the total number of characters in the string.
  2. charAt() – Fetches the character at a specified index.
  3. substring() – Extracts a specific portion of the string.
  4. equals() – Compares two strings for equality.
  5. toUpperCase() – Converts all characters to uppercase.
  6. replace() – Replaces a part of the string with another substring.
  7. trim() – Removes extra spaces at the beginning and end of the string.
Length of string: 22
Character at index 7: J
Substring (7 to 11): Java
Are the strings equal? true
Uppercase:   HELLO, JAVA WORLD!  
Replaced string:   Hello, Programming World!  
Trimmed string: Hello, Java World!