aspose file tools*
The moose likes Java in General and the fly likes Regarding the functioning of string literals... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regarding the functioning of string literals..." Watch "Regarding the functioning of string literals..." New topic
Author

Regarding the functioning of string literals...

Sriram Sharma
Ranch Hand

Joined: Apr 12, 2006
Posts: 92
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

Joined: Aug 26, 2008
Posts: 263
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.


SCJP 1.5(97%) My Blog
Sriram Sharma
Ranch Hand

Joined: Apr 12, 2006
Posts: 92
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

Joined: Aug 26, 2008
Posts: 263
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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding the functioning of string literals...
 
Similar Threads
Gc
Object creation
Why does discarding String pool objects waste memory?
Journal Article - The SCJP Tip Line - Strings, Literally
Object reference and object and garbage collection