The basic definition of String is “Sequence of Characters,” But String is not a primitive data type. It is a class in Java present in Java.lang package. It contains several methods to perform operations on data. When you create a string in Java, it creates an object of type string.
In Java, String is an Immutable class, which means once you create an Object for String cannot change the value for that. Whenever we try to change the value for the String, It will create a new instance for that. So, you can use StringBuffer and StringBuilder classes to create a mutable string.
There are two ways to create a string object.
1. String Literal
2. By using new Keyword
In this method, a string is created using double-quotes.
String s1 = “Hello”;
Whenever we create sting using string literal JVM checks for the same String are available in the “String pool.” If it is available, then the same instance is returned if it is not available, a new object created in the pool.
By using the new Keyword:
In this method, we create a String object using a new keyword, which is a common way of creating an object in Java. This method is a non-pool method.
String str = new String(“Hello”);
Commonly used methods:
int length() : Returns length of the String
boolean isEmpty() : Return boolean value(true/false) after checking whether the string is Empty or Not.
String concat(String str): Returns string value after concatenates the specified string.
String toUpperCaser() : Returns string uppercase.
String toLowerCase() : Returns string lowercase.
String trim(): Returns string after removing the space before and after.
boolean equals(Object obj): Returns true if it is matched with specified string, else returns false.
boolean equalsIgnoreCase(Object obj): It works the same as equals but, this method is not case sensitive.