Forums Register Login

Need help with Strings..

+Pie Number of slices to send: Send
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?


+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
I think both pete and soh have done a nice effort. However, if you need further research, go for this nice article
It's fun to be me, and still legal in 9 states! Wanna see my tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1001 times.
Similar Threads
please help!- what is the result of this code
Concept of intern
Difference in Creation of String Objects
WHEN ARE TWO STRINGS EQUAL?
equals() and ==
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 20:07:00.