Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes All about Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "All about Strings" Watch "All about Strings" New topic
Author

All about Strings

Manish Chhetri
Greenhorn

Joined: Oct 31, 2003
Posts: 11
What is the difference between String x="hello"; and String x=new String("hello") in terms of the object creation and the reference. Is there any difference in the way memory is allocated for these two type of String declarations.


The One..
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,
Welcome to JavaRanch!
In the first case (without the new) the String comes from a pool of unique strings held internally by the JVM; literal Strings are put into this pool when the classes defining them are loaded. In the second case, a new String object is allocated at that point while the program is executing.


[Jess in Action][AskingGoodQuestions]
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
All string constants are dumped into the CONSTANT_POOL at compile time. In the following example:

When this compiles there are two string constants placed in the constant pool, one for "A string" and one for "B string". However at runtime both 'one' and 'two' would reference the same string, while new string instances would be created for 'three', 'four' and 'five', as Ernest pointed out.
So "one == two" would evaluate to "true", but any other combination of strings would evaluate to "false" when doing an "==". That's why it's always safest to use ".equals()" when doing string comparison, unless you actually want to see if the two strings reference the same underlying String instance.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: All about Strings