Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding the functioning of string literals...

 
Sriram Sharma
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I happened to read the journal by Corey written in 2004 - http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
Was happy to know few things... though...
Why is it required for String objects to have references from two locations, when they are created as string literals?
For eg...
String a = "Ram";
"Ram" object is referred from the local variable table and from the string literal pool (constant table)
String a = new String("Ram");
In this case, "Ram" object is referred only from local variable table
What is the reason for such a design?
Any ideas please.....!!!

Regards,
Sriraam
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String a = new String("Ram");
In this case, "Ram" object is referred only from local variable table


This is not true always. If "Ram" doesn't exist in the pool then it's reference will be put in both but if it already exist in pool table it will not be kept there.
 
Sriram Sharma
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the prompt reply Shiv...
But, I think, the literal pool will be seen only incase of declaration like
String a = "Ram";

In case of
String a = new String("Ram")
I believe a new object "Ram" will be created in the heap (even without seeing the literal pool) and referred from the local variable table.

Correct me if I am wrong!

Regards,
Sriram
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome!
But Whatever I mentioned in my previous post is correct. I am quoting below lines form Kathy & Bert book for scjp 1.6.
String s = new String("abc"); // creates two objects,
// and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the pool.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic