The easiest way of creating and initializing a String object is based on string literals:
String str1 = "You cannot touch me!";
3.10.5 String Literals
A string literal is always of type String. A string literal always refers to the same instance of class String.
Each string literal is a reference (�4.3) to an instance (�4.3.1, �12.5) of class String (�4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (�15.28)-are "interned" so as to share unique instances, using the method String.intern.
Thus, the test program consisting of the compilation unit (�7.3):
and the compilation unit:
produces the output:
This example illustrates six points:
- Literal strings within the same class (�8) in the same package (�7) represent references to the same String object (�4.3.1).
- Literal strings within different classes in the same package represent references to the same String object.
- Literal strings within different classes in different packages likewise represent references to the same String object.
- Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals.
- Strings computed at run time are newly created and therefore distinct.
- The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.
Originally posted by Kaushik Badiyani:
How many String objects are created ??
I think it is 2.
2 objects "abc" and "zzz" in the String pool
2 objects "abc" and "abczzz" in the heap