A string is a char[]
containing a series of UTF-16 code units, an int
offset into that array, and an int
length.
For example.
String s
It creates space for a string reference. Assigning copies references around but does not modify the objects to which those references refer.
You should also be aware that
new String(s)
doesn't really do anything useful. It merely creates another instance backed by the same array, offset, and length as s
. There is very rarely a reason to do this so it is considered bad practice by most Java programmers.
Java double quoted strings like "my string"
are really references to interned String
instances so "bar"
is a reference to the same String instance regardless of how many times it appears in your code.
The "hello" creates one instance that is pooled, and the new String(...)
creates a non-pooled instance. Try System.out.println(("hello" == "hello") + "," + (new String("hello") == "hello") + "," + (new String("hello") == new String("hello")));
and you should see true,false,false