Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

java - String object is immutable but reference variable is mutable. What does that mean?

I was studying Kathy Sierra Java book. I came across one question something like this:

public class A {
    public static void main(String args[]){
        String s1 = "a";
        String s2 = s1;
        //s1=s1+"d";
        System.out.println(s1==s2);
    }
}

output: true

Two points I didn't understand here are:

  1. when I uncomment s1 = s1 + "d" output changes to false. Same thing happens if I replace String with wrapper Integer or int.
  2. Again, when I change my code to use StringBuffer like this:

    StringBuffer sb = new StringBuffer("a"); 
    StringBuffer sb2 = sb;
    //sb.append("c");
    System.out.println(sb == sb2);
    

    now the output doesn't changes i.e. it remains true even if I uncomment the sb.appendstatement.

I can't understand this strange behavior. Can some one explain me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

s2 is a reference to s1 in the first case. In the second case, + is translated to s1.concat("d") which creates a new string, so the references s1 and s2 point to different string objects.

In the case of StringBuffer, the reference never changes. append changes the internal structure of the buffer, not the reference to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...