Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String is interned. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String is interned." Watch "String is interned." New topic
Author

String is interned.

Ashu Jain
Ranch Hand

Joined: Feb 24, 2008
Posts: 73
As we know that string in hava is interned.
that is
String a1 = "hello friend";
String a3 = "hello" + "friend"

This will create 1 object and a3 will use existing string from pool.

I have two queries

(A) If we say System.out.println("My Problem is" + a3);
Does this creates another object "My Problem is" in string pool Or is this pooling applicable on only compile time constants.

(B) K&B says
String can2 = "7Up"
String word = "Up"
String can4 = "7" + word // This is not compile time constant

Since can4 is not compile time constant therefore it will use new string object rather than 7Up. Does that mean strings constants at compile time only use string pool.

Just confused

Ashu Jain
Ranch Hand

Joined: Feb 24, 2008
Posts: 73
Any updates on this.
Eric Daly
Ranch Hand

Joined: Jul 11, 2006
Posts: 143
From my understanding, a new object is created for every string literal, and added to the string pool. These are the compile-time constants. Every time you type a string in quotes, that is considered a string literal, and if it doesn't match a string already in the string pool when you compile, it is added. So, first of all, based on this understanding,

creates FOUR objects (not just one as you had claimed). The three string literals, "hello friend", "hello", and "friend" are added to the pool during compilation. The fourth object, created and referenced by a3, is the string "hellofriend" which is not in the string pool, because it's created at runtime. Let's say you meant to say

(which is what I'm guessing), then there would still be FOUR objects created, because the assignment

is at runtime, so the compiler will not check the string pool for any matches.
Correct me if I'm wrong, but this is my understanding, from the K&B book.


Studying for SCJP 6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String is interned.
 
Similar Threads
Garbage collection & string literal pool
JTable refreshment -- or was that 7up?
String related query
Strings
Ques on intern