Java program using all string methods

 Here's an example Java program that uses all the String methods 


public class StringExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        int len = str.length(); // length() method
        System.out.println("Length of the string: " + len);

        char ch = str.charAt(4); // charAt() method
        System.out.println("Character at index 4: " + ch);

        String sub1 = str.substring(7); // substring(int beginIndex) method
        System.out.println("Substring from index 7 to end: " + sub1);

        String sub2 = str.substring(0, 5); // substring(int beginIndex, int endIndex) method
        System.out.println("Substring from index 0 to 5: " + sub2);

        int index1 = str.indexOf('o'); // indexOf(char ch) method
        System.out.println("Index of 'o': " + index1);

        int index2 = str.indexOf("World"); // indexOf(String str) method
        System.out.println("Index of 'World': " + index2);

        String newStr1 = str.replace('o', 'x'); // replace(char oldChar, char newChar) method
        System.out.println("Replace 'o' with 'x': " + newStr1);

        String newStr2 = str.replace("World", "Universe"); // replace(CharSequence oldStr, CharSequence newStr) method
        System.out.println("Replace 'World' with 'Universe': " + newStr2);

        String upperStr = str.toUpperCase(); // toUpperCase() method
        System.out.println("Uppercase string: " + upperStr);

        String lowerStr = str.toLowerCase(); // toLowerCase() method
        System.out.println("Lowercase string: " + lowerStr);
    }
}

This program creates a String object with the value "Hello, World!" and then uses various methods to manipulate and extract information from the string. When you run the program, it will output the following:


Length of the string: 13
Character at index 4: o
Substring from index 7 to end: World!
Substring from index 0 to 5: Hello
Index of 'o': 4
Index of 'World': 7
Replace 'o' with 'x': Hellx, Wxrld!
Replace 'World' with 'Universe': Hello, Universe!
Uppercase string: HELLO, WORLD!
Lowercase string: hello, world!

Post a Comment

0 Comments