Java Strings Class

String is a sequence of character in java, widely used as object.

Strings Initialization in Java

There are two ways to declare a string in Java, and the most common way to create a string is to write:
Example:
String name = "Alex";
Through char array:
public class Sample {

    public static void main(String args[]) {
        char[] nameArray = {'A', 'l', 'e', 'x'};
        String name = new String(nameArray);
        System.out.println(name);
    }
}
Program Output:
java-string-class1

Concatenating Strings

concat() method can be used to attach strings.
Example:
public class Sample {

    public static void main(String args[]) {
        String str1 = "Hello ", str2 = "World!";
        System.out.println(str1.concat(str2));
    }
}
+ operator is more commonly used to attach strings.
"Hello," + " world" + "!"
Program Output:
java-string-concat

Java String Case

Java toUpperCase() and toLowerCase() method is used to change string case.
Example:
public class Sample {

    public static void main(String args[]) {
        String str1 = "Hello";
        System.out.println(str1.toUpperCase());
        System.out.println(str1.toLowerCase());
    }
}
Program Output:
java-string-case

Java Trim String

Java trim() method is used to eliminates white spaces before and after string.
Example:
public class Sample {

    public static void main(String args[]) {
        String str = " Hello ";
        System.out.println(str.trim());
    }
}
Program Output:
java-string-trim

Java String length

Java length() method is used to get length of the string.
Example:
public class Sample {

    public static void main(String args[]) {
        String str = "Cloud";
        System.out.println(str.length());
    }
}
Program Output:

java-string-length

No comments:

Post a Comment