The Java String is immutable which means it cannot be changed.
Whenever we change any string, a new instance is created. For mutable
strings, you can use StringBuffer and StringBuilder classes.
We will discuss immutable string later. Let's first understand what String
in Java is and how to create the String object.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String class
is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the
pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool
that is why it will create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new object but will
return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant
pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created
if it exists already in the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one refer
ence variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant
pool. The variable s will refer to the object in a heap (non-pool).
Java String Example
StringExample.java
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyw
ord
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Test it Now
Output:
java
strings
example
The above code, converts a char array into a String object. And displays
the String objects s1, s2, and s3 on console using println() method.
Immutable String in Java
A String is an unavoidable type of variable while writing any application
program. String references are used to store various attributes like
username, password, etc. In Java, String objects are immutable.
Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new
String object is created.
Let's try to understand the concept of immutability by the example given
below:
Testimmutablestring.java
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immut
able objects
6. }
7. }
Test it Now
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with Sachin Tendulkar. That is why
String is known as immutable.
As you can see in the above figure that two objects are created
but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to
"Sachin Tendulkar" object.
For example:
Testimmutablestring1.java
class Testimmutablestring1{
1. public static void main(String args[]){
2. String s="Sachin";
3. s=s.concat(" Tendulkar");
4. System.out.println(s);
5. }
6. }
Test it Now
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still
Sachin object is not modified.
Why String objects are immutable in Java?
As Java uses the concept of String literal. Suppose there are 5 reference
variables, all refer to one object "Sachin". If one reference variable
changes the value of the object, it will be affected by all the reference
variables. That is why String objects are immutable in Java.
Following are some features of String which makes String objects
immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument. Consider, if the
String object is modifiable, the value might be changed and the class that
is supposed to be loaded might be different.
To avoid this kind of misinterpretation, String is immutable.
2. Thread Safe:
As the String object is immutable we don't have to take care of the
synchronization that is required while sharing an object across multiple
threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further
errors by loading the correct class. This leads to making the application
program more secure. Consider an example of banking software. The
username and password cannot be modified by any intruder because
String objects are immutable. This can make the application program
more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap
memory. When we try to declare a new String object, the JVM checks
whether the value already exists in the String pool or not. If it exists, the
same value is assigned to the new object. This feature allows Java to use
the heap space efficiently.
Why String class is Final in Java?
The reason behind the String class being final is because no one can
override the methods of the String class. So that it can provide the same
features to the new String objects as well as to the old ones.
Java String compare
We can compare String in Java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by
compareTo() method), reference matching (by == operator) etc.
There are three ways to compare String in Java:
1. By Using equals() Method
2. By Using == Operator
3. By compareTo() Method
1) By Using equals() Method
The String class equals() method compares the original content of the
string. It compares values of string for equality. String class provides the
following two methods:
o public boolean equals(Object another) compares this string to the
specified object.
o public boolean equalsIgnoreCase(String another) compares this
string to another string, ignoring case.
Teststringcomparison1.java
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
Test it Now
Output:
true
true
false
In the above code, two strings are compared using equals() method
of String class. And the result is printed as boolean values, true or false.
Teststringcomparison2.java
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2));//true
8. }
9. }
Test it Now
Output:
false
true
In the above program, the methods of String class are used.
The equals() method returns true if String objects are matching and both
strings are of same case. equalsIgnoreCase() returns true regardless of
cases of strings.
2) By Using == operator
The == operator compares references not values.
Teststringcomparison3.java
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance c
reated in nonpool)
8. }
9. }
Test it Now
Output:
true
false
3) String compare by compareTo() method
The above code, demonstrates the use of == operator used for comparing
two String objects.
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically
and returns an integer value that describes if first string is less than, equal
to or greater than second string.
Suppose s1 and s2 are two String objects. If:
o s1 == s2 : The method returns 0.
o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.
Teststringcomparison4.java
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10.}
Test it Now
Output:
0
1
-1