String Class

The String class in Java is used to represent a sequence of characters. It is an immutable class, which means that once a string is created, its value cannot be changed. The class provides a number of useful methods to perform various operations on strings. Here are some common methods of the String class:

  1. length(): Returns the length of the string.

  2. charAt(int index): Returns the character at the specified index.

  3. substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string.

  4. concat(String str): Concatenates the specified string to the end of this string.

  5. equals(Object obj): Compares this string to the specified object for equality.

  6. compareTo(String anotherString): Compares this string to another string.

  7. toLowerCase(): Converts all of the characters in this string to lower case.

  8. toUpperCase(): Converts all of the characters in this string to upper case.

  9. trim(): Returns a new string that is a copy of this string with leading and trailing white space removed.

  10. indexOf(int ch): Returns the index within this string of the first occurrence of the specified character.

  11. lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified character.

  12. contains(CharSequence s): Returns true if this string contains the specified sequence of char values.

  13. replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

  14. startsWith(String prefix): Tests if this string starts with the specified prefix.

  15. endsWith(String suffix): Tests if this string ends with the specified suffix.

String class example in Java

refer‮‬ to:theitroad.com
public class StringExample {
    public static void main(String[] args) {
        // Create a String object
        String str = "Hello, World!";
        System.out.println("String is: " + str);

        // Get the length of the string
        int length = str.length();
        System.out.println("Length of the string is: " + length);

        // Convert the string to uppercase
        String upperCase = str.toUpperCase();
        System.out.println("Uppercase string is: " + upperCase);

        // Convert the string to lowercase
        String lowerCase = str.toLowerCase();
        System.out.println("Lowercase string is: " + lowerCase);

        // Check if the string contains a particular substring
        boolean contains = str.contains("World");
        System.out.println("Does the string contain 'World'? " + contains);

        // Replace a substring in the string with another substring
        String replaced = str.replace("World", "Java");
        System.out.println("Replaced string is: " + replaced);
    }
}