File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes String Pool Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String Pool" Watch "String Pool" New topic

String Pool

S Majumder
Ranch Hand

Joined: Jun 03, 2009
Posts: 346
Hi everybody, I have one question related String .

So in this case when str3 will creating the string is it takes the value from the string literal pool (that already being created by the str1) or it will create a new string ?

Thanks ,

vinayak jog
Ranch Hand

Joined: Apr 01, 2011
Posts: 81

hello, s begri

it ll create a new string
S Majumder
Ranch Hand

Joined: Jun 03, 2009
Posts: 346
Hi vinayak jog ,

Thanks for your reply , could you please explain this .

I have another problem

Why it is printing false ?

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

When you use the == operator on objects, you are comparing the REFERENCE - i.e. are the two variables pointing to the same spot in memory (more or less). Any time you use the "new" operator, you create a new object. When you do you get one string in the String Pool, and ANOTHER string is created on the stack. When you do it again, the same String pool string is used to create ANOTHER String on the stack.

So, with the code you show, you have one string of "123" in the String pool, and two additional objects in the stack.

You then compare if the two reference variable point to the same spot in memory, and since they are different objects on the stack, they do not. So, you get false.

If you had done

you should get true.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
S Majumder
Ranch Hand

Joined: Jun 03, 2009
Posts: 346
I agree. Here's the link:
subject: String Pool
It's not a secret anymore!