is String created by literal primitive or referenced type?

i'm already tired but i'm wondering if (see the topic).

String a = "first";
    String b = "second";
    a = b;
    b = "third";
    System.out.println(a + ", " + b);

-my question is why i got the output: "second, third". Isn't is String referenced type? So after command "a = b;" why didnt change both of variables? Wasn't both variables referencing to the same object? (or the same String from the String pool?)

Jon Skeet
people
quotationmark

Isn't is String referenced type?

Yes, String is a reference type.

So after command "a = b;" why didnt change both of variables?

Because you only said to change the value of one variable at a time.

This statement:

b = "third";

only changes the value of b. It changes it to refer to a different string. The value of a remains as it was before - a reference to a string with contents "second".

It's very important to distinguish between these concepts:

  • Variables
  • Values
  • References
  • Objects

When you write:

a = b;

That just means "take the current value of b, and make it the new value of a." It doesn't say "make a and b equivalent variables, so that any change to the value of either variable affects the other variable". When you change the value of b in the next line to refer to a different object, that does nothing to either a or the object that the value of a refers to.

Now I suspect you were being confused because of code like this:

StringBuilder a = new StringBuilder();
StringBuilder b = a;
a.append("foo");
System.out.println(b); // Prints foo

In this case the a.append() call doesn't change the value of a or b at all... both variables still have values which refer to the same StringBuilder object. The append method instead changes the data within that object... so when you print the contents of the object in the final line, getting at it via b, you still see foo because you're still referring to the same (modified) object.

people

See more on this question at Stackoverflow