Java Challeng (2) Answer

Well, the comments are right.

public class Test {
          public static void main(String[] args) {
                         String s1 = new String(”Test 2″);
                         String s2 = s1;
                         System.out.println(”s2 = ” + s2);
                         s1 = s1 + ” modified”;
                         System.out.println(”s2 = ” + s2);

The code above will print:

Test 2
Test 2

However, the real reason of that is a particularity of the String class. For any other object type, where two references refer to the same object, if either reference modify the object, both references will see the change because there is still only a single object. But any time we make any changes to a String, the Virtual Machine will update the reference variable to refer to a different object.

After the assignment,  s1 and s2 variables refer to diferrent String objects, so the reference used to modify the String refer to the new object, which not modify the older one.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s