File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Pool

 
S Majumder
Ranch Hand
Posts: 349
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ,
S

 
vinayak jog
Ranch Hand
Posts: 81
MySQL Database Netbeans IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello, s begri

it ll create a new string
 
S Majumder
Ranch Hand
Posts: 349
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi vinayak jog ,

Thanks for your reply , could you please explain this .

I have another problem



Why it is printing false ?

regards,
S
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12017
24
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
S Majumder
Ranch Hand
Posts: 349
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic