A string is a sequence of character in Java, widely used as an 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:
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 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 Trim String
Java trim() method is used to eliminates white spaces before and after a string.
Example:
public class Sample {
public static void main(String args[]) {
String str = " Hello ";
System.out.println(str.trim());
}
}
Program Output:
Java String length
Java length() method is used to get the length of the string.
Example:
public class Sample {
public static void main(String args[]) {
String str = "Cloud";
System.out.println(str.length());
}
}
Program Output: