Java String variable setting - reference or value?

后端 未结 9 810
感动是毒
感动是毒 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:49

    The assertion

    if Java treats String variables like references to any other Object, the answer would be "abc abc"

    is incorrect. Java does treat String variables like references to any other Object. Strings are Objects but the answer is "abc ab" none the less.

    The issue is not what the assignment operator does. The assignment operator assigns a reference to a String object in every case in your example.

    The issue is what the concatenation operator ('+') does. It creates a new String object. As other have said, this is necessary because a String object is immutable but it is an issue of operator behaviour and not merely because String is immutable. The concatenation operator could return a new Object even if a String object were mutable.

    In contrast, in your second example, b1.setBalance(0) does not create a new object, it modifies the existing object.

提交回复
热议问题