|
![]() |
Igor Gaschits,<br />JSCP
The easiest way of creating and initializing a String object is based on string literals:
String str1 = "You cannot touch me!";
[I]
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:
[/I]
- 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:
String s1,s2,s3,s4;
s1="abc";
s2=s1;
s3=s2+"zzz";
s4=s3;
How many String objects are created ??
I think it is 2.
Ashik Uzzaman
Engineering Manager, Marqeta, Oakland, CA, USA
Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Ashik Uzzaman
Engineering Manager, Marqeta, Oakland, CA, USA
Result:
2 objects "abc" and "zzz" in the String pool
2 objects "abc" and "abczzz" in the heap
Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Destiny's powerful hand has made the bed of my future. And this tiny ad:
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
|