Understanding String Immutability in Java -


while trying understand reasons behind why strings immutable, wrote simple program follows:

/* program test string immutability */  public class stringimmutability {     public static void main(string args[])     {         string s = "hello";         s.concat(" world"); // returns new string object. so, reference must point object further processing this: s = s.concat(" world");         system.out.println(s);         s = s.concat(" world");         system.out.println(s);         string s1 = s, s2 = s, s3 = s;         system.out.println(s1+" "+s2+" "+s3);         s = s.concat(" test");         //the references modified         system.out.println(s1+" "+s2+" "+s3);      } } 

the output though isn't expected:

hello hello world hello world hello world hello world hello world hello world hello world 

after references modified, output must hello world test repeated thrice there isn't change in output.

it working expected. let's @ step step:

string s = "hello"; s.concat(" world"); 

enter image description here

this nop because not assigning result of concat anything. new string instance lost ether , garbage collected since there nothing referring it. hence, s remains unchanged.

s = s.concat(" world"); 

enter image description here

here s.concat(" world") returns new string instance, , have reassigned s that. s points new string , have lost reference older 1 (the 1 had hello in it).

string s1 = s, s2 = s, s3 = s; 

enter image description here

here have created 3 variables point same string instance s points to.

s = s.concat(" test"); 

enter image description here

this repeat of did earlier. concat creates new string instance , reassign s that. keep in mind s1, s2, , s3 still pointing s used to point , not reflect changes.

you've stopped s pointing old string , made point new one. other variables still pointing old string.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -