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:

  1. when uncomment s1 = s1 + "d" output changes false. same thing happens if replace string wrapper integer or int.
  2. again, when change code use stringbuffer this:

    stringbuffer sb = new stringbuffer("a");  stringbuffer sb2 = sb; //sb.append("c"); system.out.println(sb == sb2); 

    now output doesn't changes i.e. remains true if uncomment sb.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

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -