String foo
itself is just a reference. Since it is a String-reference it is able to reference a String from what's called the 'String Pool', an implementation of String Intering. It however does not create a new String.
Neither does
String bar = null;
String bar is, just as foo, a String reference, but creating a reference does not create a new Object. The difference between foo
and bar
is that bar is assignet to null
but null is surely not a String and therefore the JVM has no reason to create a new String.
Your last assumption however comes closer to what actually happens.
String foo = "Hello World";
does create a new String (assuming "Hello World" was not found in the String Pool yet).
You can split up this statement into three smaller statements:
- Create Reference
String foo
creates a new reference, capable of referencing a String Object
- Creating Object
"Hello World"
, as a short form for new String("Hello World")
allocates spaces on the Object Heap (in this case the String Pool) and actually creates the new Object.
- Assignment
=
finally assigns our Object with our reference.
To sum everything up: neither of
String x;
String y = null;
will create a new String. But both of those statements will
x = "Hello";
y = "Hey";