Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help with Strings..

 
Wee Keong Soh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think both pete and soh have done a nice effort. However, if you need further research, go for this nice article
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic