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:
- when I uncomment
s1 = s1 + "d"
output changes to false
. Same thing happens if I replace String with wrapper Integer
or int
.
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.append
statement.
I can't understand this strange behavior. Can some one explain me.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…