Java Strings
A String variable contains a sequence of characters surrounded by double quotes. An array of characters works same as string in java. Strings are immutable.
1. Creating string object:
There are two ways to create String object:
i) By string literal
ii) By new keyword
i) By string literal:
Java String literal is created by using double quotes assigned to the string variable.
syntax:
String string_name = "value";
Example:
String greeting = "Welcome to ShapeAI";
ii) By new keyword:
Using new keyword, string object is created with double quotes.
syntax:
String string_name = new String("value");
Example:
String greeting = new String("Welcome to ShapeAI");
2. String Functions:
Java String provides various string functions to perform different operations on strings.
i) String length():
The String length() method tells the length of the string. It returns the count of the total number of characters present in the String.
Example:
class LengthExample {
public static void main(String args[] {
String s1 = "Welcome";
String s2 = "Java";
System.out.println("string length : " + s1.length());//string length
System.out.println("string length : " + s2.length());//string length
}
}
/*OUTPUT:
string length : 7
string length : 4 */
ii) String concat():
The Java String concat() method combines a specific string at the end of another string and returns a combined string.
Example:
class ConcatExample {
public static void main(String args[]) {
String s1 = "Welcome";
s1 = s1.concat("to ShapeAI");
System.out.println(s1);
}
}
/*OUTPUT:
Welcome to ShapeAI */
iii) String compareTo():
The Java String compareTo() method compares the given string with current string.
Example:
public class CompareToExample {
public static void main(String args[]) {
String s1 = "hello";
String s2 = "hello";
String s3 = "cello";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); /* 5 because "h" is five
times higher than "c" */
}
}
iv) String IsEmpty() :
This method checks whether the String contains value or not. If the java String is Empty, it returns true otherwise returns false.
Example:
public class IsEmptyExample {
public static void main(String args[]) {
String s1 = "";
String s2 = "welcome";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}
}
v) String toLowerCase() :
The java string toLowerCase() method converts all the characters of the String to lower case.
Example:
public class StringLowerExample {
public static void main(String args[]) {
String s1 = "WELCOME TO JAVA”;
String lower = s1.toLowerCase();
System.out.println(lower);
}
}
/*OUTPUT:
welcome to java */
vi) String toUpper() :
The Java String toUpperCase() method converts all the characters of the String to upper case.
Example:
public class StringUpperExample {
public static void main(String args[]) {
String s1 = "welcome to java";
String upper = s1.toUpperCase();
System.out.println(upper);
}
}
/*OUTPUT:
WELCOME TO JAVA */