Sitansu Sitansu - 3 months ago 7x
Java Question

String immutable?

Can anyone answer me please?

public class ReplaceString{

public static void main(String arg[]) {
String a = "Hariom";
a = a.replace('H', 'b');


A String is immutable, which means you cannot change the string value on the same address. If you change it, it will create a new object and you have to assign it to the current string object. For example,

 String a = "Hariom";
 a.replace('H', 'b');
 System.out.println(a);   //will print "Hariom"

because a is not changed. Instead, you created a new String in memory with the value bariom and to show that change to a, you have to point the newly created string to a, i.e.

a= a.replace('H', 'b');

Maybe this would be a bit more clear:

Step 1: String a = "Hariom"; you create a new string in memory and the variable a points to it.

enter image description here

Step 2: a.replace('H', 'b'); if you replace some character in String a, a new String is created in the heap with no variable pointing to it.

enter image description here

Step 3: a= a.replace('H', 'b'); if you call replace() and assign it to the variable a, what happens is that the new String bariom is created in the heap. Then you assign it to a causing a to point to the new String.

enter image description here