java - String object is immutable but reference variable is mutable. What does that mean? -
i studying kathy sierra java book. came across 1 question this:
public class { public static void main(string args[]){ string s1 = "a"; string s2 = s1; //s1=s1+"d"; system.out.println(s1==s2); } } output: true
two points didn't understand here are:
- when uncomment
s1 = s1 + "d"output changesfalse. same thing happens if replace string wrapperintegerorint. again, when change code use
stringbufferthis:stringbuffer sb = new stringbuffer("a"); stringbuffer sb2 = sb; //sb.append("c"); system.out.println(sb == sb2);now output doesn't changes i.e. remains
trueif uncommentsb.appendstatement.
i can't understand strange behavior. can 1 explain me.
s2 reference s1 in first case. in second case, + translated s1.concat("d") creates new string, references s1 , s2 point different string objects.
in case of stringbuffer, reference never changes. append changes internal structure of buffer, not reference it.
Comments
Post a Comment