Java String variable setting - reference or value?

后端 未结 9 813
感动是毒
感动是毒 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 02:05

    In Java, String objects are assigned and passed around by reference; it this respect they behave exactly like any other object.

    However, Strings are immutable: there isn't an operation that modifies the value of an existing string in place, without creating a new object. For example, this means that s1 = s1 + "c" creates a new object and replaces the reference stored in s1 with a reference to this new object.

提交回复
热议问题