Lucas
Lucas

Reputation: 5069

In Java, Strings are immutable, so what exactly happens when do this?

String s;
/*code*/
s = "foo";

Is a whole new object being created, since the empty string can't change?

Upvotes: 1

Views: 131

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272707

This:

String s;

doesn't create an "empty string", it's simply an uninitialised variable.

This:

s = "foo";

sets that variable to refer to a String object. It's the object that's immutable, not the variable.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1503290

You need to understand the difference between variables and objects.

Consider this code:

String x = "hello";
for (int i = 0; i < 10; i++) {
    x = x + i;
}

This will end up creating 11 string objects, but there are only two variables involved (x and i). At any point, the value of i is an integer (0-10) and the value of x is a reference to a String. (It could be null too, but it happens not to be in this example.)

It's important to understand that x is not an object, nor is the value of x an object.

If it helps to think of it in physical terms, consider a piece of paper with my home address on it:

  • The piece of paper is like the variable - it's "somewhere a value can be stored".
  • The address written on the piece of paper is like the reference - it's a way of finding an object
  • The house itself is like the object.

Neither the piece of paper nor the address is the house itself. If you rub the address out on the paper and write a different address instead, that doesn't make any changes to my house - just like changing the value of x doesn't make any changes to the string objects themselves in my sample code.

Upvotes: 5

Louis Wasserman
Louis Wasserman

Reputation: 198471

s isn't currently assigned to anything at all.

But if you had -- if you had defined String s = ""; and then s = "foo";, then the empty string isn't changed, but the variable s is changed to refer to the string "foo" instead of the empty string.

Upvotes: 2

Related Questions