Java String variable setting - reference or value?

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

    java.lang.String is an object, not a primitive.

    What the code did in the first example is:

    1. Define s1 as "ab"
    2. Set s2 equal to the same underlying object as s1
    3. Set s1 equal to a new string that is the combination of s1's old value and "c"

    But to answer your question about reference or value, it's by reference.

提交回复
热议问题