This post talks about one of the very important class; String in Java. In Java String class represents character strings which means; Strings in Java are objects and all created strings are instances of the String class in Java. In String class strings are internally stored as character array.
How to create String in Java
You can create a String object using-
- new operator
- Using String literal
1. Using new operator
Since strings are objects so strings can of course be created using new operator. String class has more
than 10 constructors to create Strings in Java which ranges from taking nothing as parameter to taking char array,
StringBuffer, StringBuilder, another String as argument. For Example
String str = new String(“abc”);
2. Using String literal
Preferred way to create Strings is to assign String literal directly to a String reference as
you will do for any primitive type. For every String literal Java automatically constructs a String object. For Example
String str = “abc”;
String pool in Java
But having String literals brings another dimension to storing String in Java. If String objects are created using new operator, objects
will go in the heap with their own space. String literals are treated differently they are stored
in a String pool and that is a common pool; which means if there are two strings literals having the same
content then those string will share the space in the pool.
When String object is created by assigning a string literal, pool will be checked to verify if there is
any existing object with the same content if there is then that existing reference is used, no new object
is created in that case. If no object is found with the same content then this new literal will be added in the pool.
For example, if two strings str1 and str2 are created as follows-
String str1 = "abc";
String str2 = "abc";
Then the string object reference is shared between these two literals.
String pool in Java
Let’s see it with an example–
In this program two string literals will be created with the same content and then these two string objects are
checked for reference equality. Since we are not comparing the content but the references of two objects so
“==” operator will be used.
public class StringDemo {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
if(str1 == str2){
System.out.println("str1 and str2 are same");
}else{
System.out.println("str1 and str2 are not same");
}
}
}
Output
str1 and str2 are same
Refer
String Pool in Java to know more about String pool.
Java String intern() method
Using Java String's intern()
method you can still get string object from the pool (if it exists) even if new operator is
used to create a string.
When the intern method is invoked, if the pool already contains a string equal to this String object as
determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String
object is added to the pool and a reference to this String object is returned.
In the previous Java program if str4 is changed to have interned string then the code will look like–
public class StringDemo {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
if(str1 == str2){
System.out.println("str1 and str2 are same");
}else{
System.out.println("str1 and str2 are not same");
}
String str3 = new String("abc");
String str4 = new String("abc").intern();
if(str3 == str4){
System.out.println("str3 and str4 are same");
}else{
System.out.println("str3 and str4 are not same");
}
if(str1 == str4){
System.out.println("str1 and str4 are same");
}else{
System.out.println("str1 and str4 are not same");
}
}
}
Output
str1 and str2 are same
str3 and str4 are not same
str1 and str4 are same
It can be seen that str1 and str4 are having the same reference now.
Java String is immutable
Once you create a String object the content of that string cannot be modified. As we have already seen
Java maintains a string pool where references are shared thus changing content of any of the String will
also affect the other strings sharing the same references that’s one reason why String is immutable in Java.
Here being
immutable means whenever you perform any operation on string which alters its content a new string
object is created which contains the modified string. Original string is left as it is. If there are no
references to the original string it is garbage collected.
Using any of the methods that modify the original String like toLowerCase, toUpperCase, concatenating
using concatenate() method or ‘+’ operator will result in creation of a new string object.
Let's try to see the immutability of the String using as example.
String str = "hello";
str.concat("world");
System.out.println("Value of str- " + str);
Output
Value of str- hello
You can see that the original String is not changed, when the concatenation is done a new String object is created.
Refer
Why is String Immutable in Java to know more about immutable strings and why are strings immutable in Java.
String class in Java is final
As already mentioned above whenever you perform any operation on string which alters its content a new string
object is created containing the modified string. Which means all the methods of the String class in Java that modify
the content in any way return a new String object with the modified content.
Now, what if you can override the method of the String class and provide an implementation to modify the content of the
String and return the original String itself? What will happen to the String pool then where strings having the same
data share the same reference?
Another scenario- You extend the String class and override hashCode() and equals() method in such a way that
two dissimilar strings return the same hashCode and at the same time equals() return true. Then you can have
different strings sharing the same reference in the String pool.
To avoid these kind of scenarios String class is declared as final in Java and it can’t be overridden.
String and thread-safety
Since String objects are immutable thus thread-safe.
Refer
Is String Thread Safe in Java to know more about String and thread safety.
Overloaded operators in String
Apart from using concatenate method to concatenate two strings ‘+’ operator can be used to do the same.
Actually + and += are two operators which are overloaded for String in Java.
So, if you have two strings
String str1 = "Hi";
String str2 = "Hello";
You can use ‘+’ operator to concatenate them
str1 = str1 + str2;
System.out.println("str1 " + str1);
Or, to make it more concise
str1 += str2;
System.out.println("str1 " + str1);
Comparing Strings using .equals method
In the section about string pool we used == to compare references but what if you want to compare content
of two strings even if their references are different. You will have to use .equals
method in that case.
public class StringDemo {
public static void main(String[] args) {
String str1 = "abc";
String str4 = new String("abc");
// comparing content
if(str1.equals(str4)){
System.out.println("str1 and str4 are same");
}else{
System.out.println("str1 and str4 are not same");
}
// comparing references
if(str1 == str4){
System.out.println("str1 and str4 are same");
}else{
System.out.println("str1 and str4 are not same");
}
}
}
Output
str1 and str4 are same
str1 and str4 are not same
Though str1 and str4 have same content but they will have different references as str4 is created using
new operator. That is why comparing using "==" prints "str1 and str4 are not same" as references are
different but comparing using .equals prints "str1 and str4 are same", as content is compared in that case.
Java String class methods
String class has lots of methods for various operations. These String class methods can be grouped as per functionality.
- Methods for String comparison- In Java String class there are methods like equals, compareTo, regionMatches for comparing strings. Refer String Comparison in Java to see examples of comparing strings in Java.
- Methods for searching in String- If you want to find characters or substrings within a String you can use methods like
indexOf() and lastIndexOf(). Refer
Searching Within a String Using indexOf(), lastIndexOf() And contains() Methods to see examples of searching with in
a String.
- Getting specific character from String- If you are trying to get specific character from a String then you can use charAt() method.
Refer
Java String charAt() Method With Examples to see examples of getting characters from a String.
- Getting a substring- If you are trying to get substring with in a String then you can use substring() method. Refer
Getting Substring - Java String substring() Method
to see examples of getting substring from a String.
- Splitting a String- If you want to split a string into one or more substrings then you can use split() method.
Refer
Splitting a String Using split() Method in Java to see examples of splitting a String in Java.
- Merging Strings- For merging multiple strings in Java you can use join() method.
Refer
String join() Method in Java to see examples of joining Strings in Java.
- Checking String null or empty- For checking if the String is null or empty you can use isEempty(), length() or
isBlank() method. Refer
Check String Null or Empty in Java to see examples.
- intern() Method- For interning strings in Java you can use intern() method.
Refer
intern() Method in Java String to know more about interning Strings.
- matches() Method- Using matches() method you can check whether or not this string matches the given regular expression.
Refer
matches() method in Java String to see examples of matches() method.
Points to note about Java String
- Internally in String class, Strings are stored as character array.
- Strings in Java are objects and all strings are instances of the String class.
- Strings can be created by assigning String literal directly to a String reference like String str = “abc”;
which may look like assigning to a primitive data type but don't forget Strings are objects.
- String literals in Java are treated differently, they are stored in a String pool and that is a common pool.
- If there are two strings literals having the same content then those string will share the space in the pool.
- String is immutable in Java once you create a String object the content of that string cannot be modified.
- Since String is immutable in Java whenever you perform any operation on string which alters its content a new
string object is created which contains the modified string. Original string is left as it is.
- Since String is immutable it is also thread safe.
- String class is declared as final and it can’t be overridden.
- "+" operator is overloaded for String and it is used for concatenating strings.
- Using intern() method you can still get string object from the pool (if it exists) even if new
operator is used to create a string.
- For comparing the content of two strings .equals() method is used. If you want to ignore case then
use .equalsIgnoreCase().
- From Java 7 string can also be used in switch case statement.
- join() method is added in String class in Java 8 which makes it very easy to join multiple strings.
That's all for this topic String in Java Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related topics
-
StringBuffer Class in Java With Examples
- Converting Char to String And String to Char in Java
-
Converting String to int in Java
-
How to Create Immutable Class in Java
-
Java String Interview Questions And Answers
You may also like-
-
Marker interface in Java
-
Array in Java With Examples
-
How and why to synchronize ArrayList in Java
-
LinkedHashMap in Java With Examples
-
Java Exception Handling And Method Overriding
-
finally Block in Java Exception Handling
-
Java BlockingQueue With Examples
-
Java ReentrantLock With Examples