It's not a secret anymore!
The moose likes Beginning Java and the fly likes Need help with Strings.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need help with Strings.." Watch "Need help with Strings.." New topic

Need help with Strings..

Wee Keong Soh

Joined: Apr 08, 2009
Posts: 18
String mystring1 = new String("Java Rocks");
String mystring2 = new String("Java Rocks");

boolean test = mystring1 == mystring2;
boolean test1 = mystring1.equals(mystring2);

Results: test is false, test1 is true
String mystring1 = "Java Rocks";
String mystring2 = "Java Rocks";

boolean test = mystring1 == mystring2;
boolean test1 = mystring1.equals(mystring2);

Results: test is true, test1 is true

For the first block of code, test returns false because the == operator compares whether the references refer to the same object or not and not the state of the object.
Can anyone enlighten me why test returns true for the second block of code? Doesn't this way of declaring strings the same as the former way?

pete stein

Joined: Feb 23, 2007
Posts: 1561
Strings are stored in a special region of the (?) heap called the String pool. The reason being that Java likes to reuse Strings if it can. So in your second example, Java places the first String in the String pool and then reuses that very same object as the reference point of the second String variable. In your first example the new String(...) forces Java to create new String objects regardless of whether or not a similar String exists in the String pool.
Mark Barrett

Joined: May 25, 2009
Posts: 12
Pete is exactly right, except that the String pool is separate from the heap. The String objects still live on the heap, but there is a reference to it in the String pool.

SCJP: 81%
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

I think both pete and soh have done a nice effort. However, if you need further research, go for this nice article
I agree. Here's the link:
subject: Need help with Strings..
jQuery in Action, 3rd edition