The mechanism enabling you to create String
objects with string literals is built into the compiler and JVM. It is not available for use with objects of user-defined types.
When you write for the first time
String s = "sometext";
the compiler emits two things:
- A constant pool entry with
"sometext"
in it, and
- An instruction that sets
s
to reference to the entry in the constant table.
If you write
String t = "sometext";
in the same class, the compiler will reuse an existing constant for "sometext"
, rather than creating a new one.
At runtime, JVM creates a new String
object for each entry from the constant table, and gives your program access to them. Essentially, JVM invokes new
on your program's behalf, and hands it a ready-to-use object.
Similar system is in play when you create instances of primitive wrappers with autoboxing. The common thing, however, is that it requires support from the compiler, and is not available for user-defined types.