What is the string immutable in Java?
Strings are immutable in Java. That means once you create an string object you can not modify it.
Primitive types variables and object references are stored in a stack. Also, objects are stored in a Heap. Like these java stores the data in memory.
Creating a new string variable with same value.
Java looks the value of the string objects. Both name and secondName variables have same value then Java will not create a new object to store same value. Both name and secondName will refer same value in the heap.
Changing the value of string variable.
Changing the value of the string variable will make new object and link the reference name. It does not modify the existing object.
(Actually, without reference there could not be objects on heap because garbage collector remove the objects that have no references.)
Creating new string with existing value.
It can be done using “new” key word. Then two objects with same values will be created on the heap.
This article will help you to understand about string immutability of the Java.