Java — Important Conclusions about String Immutability | Code Factory

Code Factory
2 min readMay 15, 2020

Index Page : Link

Donate : Link

String s1 = new String("code factory");
String s2 = s1.toUpperCase();
String s3 = s1.toLowerCase();
System.out.println(s1 == s2); // false
System.out.println(s1 == s3); // true
  • As there is no any change in the content for s3 operation so same object value is used.
  • Object is present is Heap or SCP area, rule is same.
String s1 = "code factory";
String s2 = s1.toString();
String s3 = s1.toLowerCase();
String s4 = s1.toUpperCase();
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // true
System.out.println(s1 == s4); // false
  • In s1.toString() and s1.toLowerCase() value is not changed so s2 and s3 reference to s1.
  • In s1.toUpperCase() value changed at runtime so it is store in Heap area.

Conclusion : Once we create an object (String), it not allow any change in that object. If we are trying to perform any changes, if there is change in the content with those changes a new object will be created. If there is no changes in the content, existing object only resused.

Whatever the existing object present in the Heap or SCP area, rule is always same.

--

--