Java String variable setting - reference or value?

后端 未结 9 807
感动是毒
感动是毒 2020-11-30 01:08

The following Java code segment is from an AP Computer Science practice exam.

String s1 = \"ab\";
String s2 = s1;
s1 = s1 + \"c\";
System.out.println(s1 + \"         


        
9条回答
  •  温柔的废话
    2020-11-30 01:59

    java Strings are immutable, so your reassignment actually causes your variable to point to a new instance of String rather than changing the value of the String.

    String s1 = "ab";
    String s2 = s1;
    s1 = s1 + "c";
    System.out.println(s1 + " " + s2);
    

    on line 2, s1 == s2 AND s1.equals(s2). After your concatenation on line 3, s1 now references a different instance with the immutable value of "abc", so neither s1==s2 nor s1.equals(s2).

提交回复
热议问题