Java String variable setting - reference or value?

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

    The difference between your BankAccount and a String is that a String is immutable. There is no such thing as 'setValue()' or 'setContent()'. The equivalent example with your bank account would be :

    BankAccount b1 = new BankAccount(500); // 500 is initial balance parameter
    BankAccount b2 = b1; // reference to the same object
    b1 = new BankAccount(0);
    System.out.println(b1.getBalance() + " " + s2.getBalance()); // prints "0 500"
    

    So if you think of it this way (not actually what the compiler does, but functionally equivalent) the String concatenation scenario is:

    String s1 = "ab";
    String s2 = s1;
    s1 = new String("abc");
    System.out.println(s1 + " " + s2); //prints "abc ab"
    

提交回复
热议问题