Strings are Immutable in Java

Kasun Dissanayake
5 min readMar 11, 2022

--

In this tutorial I am going to explain Why Strings are Immutable, Immutable Objects and How to use the new keyword with Strings.

Immutable Objects

Immutable Objects are Objects whose contents can not be changed. You already know that content is a variable whose value cannot be changed. Similarly, an Immutable object is an object whose content cannot be changed. So the content referenced by the Object. Immutable Objects are created from Immutable classes. The String class in Java is Immutable. This means the content of String Objects in Java cannot be changed.

Example:

public class MyClass {
public static void main(String args[]) {
String str = "abc";
str = "cde";
System.out.println("str Value "+ str);
}
}

Here I am defining a new String variable str, and I assigned “abc” as the value of that variable. What is happening here?

Now we are going to add a new value for str.

When we print the str you will get an output like this.

It will print “cde” value only. What happens to the previous value “abc”?

It is now considered “Garbage”. It will remove from the memory by the Java Garbage Collector. We don’t have to worry about it.

Using the new keyword with Strings

Since the Strings are immutable we don’t need to use a new keyword.

Why don’t you need a new keyword while creating objects?

We would want to use a new keyword because it allows us to create a separate object that references a separate value. When working with strings this is not needed. Because the original string will not be modified since Strings are Immutable.

You don't need to create a new Object, that references a separate value. Because even if I have many Objects referencing the same value, my value will never be modified. Each time I try to modify the value a new String will be created and my original value not be affected. This is why there is no need to use a new Keyword.

Example:

Now I am going to define two string variables called str1 and str2.

public class MyClass {
public static void main(String args[]) {
String str1 = "Value1";
String str2 = str1;

System.out.println(str2);
}
}

What is happening here,

Now if you try to print str2 you will get the str1 value which is “Value1” as the Output.

Now Let’s change the str1 value to “Value2”. Let's get an understanding of what will happen here when we change it by this diagram.

Code:

public class MyClass {
public static void main(String args[]) {
String str1 = "Value1";
String str2 = str1;
str1 = "Value2";

System.out.println("Value of str1 --> " +str1);
System.out.println("Value of str2 --> " +str2);
}
}

Output:

So these all because of Strings are immutable. Even if you don't use the new keyword we still have “Value1” protected. That means you cant remove that value. Always use the “=” sign with Strings. No need to use new keywords with them.

Difference between “equals” vs “==”

  • == is a reference comparison, i.e. both objects point to the same memory location
  • .equals() evaluates to the comparison of values in the objects

With respect to the String class:

The equals() method compares the “value” inside String instances (on the heap) irrespective of whether the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances it doesn’t make a difference. It's the “value” (that is: the contents of the character array) inside each String instance that is being compared.

On the other hand, the “==” operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references “refer to” the same String instance then the result of the boolean expression would be “true”. On the other hand, the value of both object references “refer to” different String instances (even though both String instances have identical “values”, that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be “false”.

Example:

String build from string literal will be added to something called the String constant pool, e.g. String s1 = "someString"; String s2 = "someString;" both s1 & s2 will share the same reference. s1 == s2 will return true. But if they were constructed via the String constructor, e.g. String s1 = new String("someString"); String s2 = new String("someString"); then they will not share the same reference. s1 == s2 will return false.

public class Test {public static void main(String[] args){String s1 = "HELLO";String s2 = "HELLO";String s3 =  new String("HELLO");System.out.println(s1 == s2); // trueSystem.out.println(s1 == s3); // falseSystem.out.println(s1.equals(s2)); // trueSystem.out.println(s1.equals(s3)); // true}}

Explanation: Here, we create two objects, namely s1 and s2.

  • Both s1 and s2 refer to the same objects.
  • When we use the == operator for s1 and s2 comparison, the result is true as both have the same addresses in the string constant pool.
  • Using equals, the result is true because it’s only comparing the values given in s1 and s2.

I hope you will get an idea about Strings that are Immutable in Java and some idea about the “equals” method and “==” operator. See you in another tutorial.

Thank you!

--

--

Kasun Dissanayake

Senior Software Engineer at IFS R & D International || Former Software Engineer at Pearson Lanka || Former Associate Software Engineer at hSenid Mobile