Forums Register Login

string related question

+Pie Number of slices to send: Send
program:
class strc
{
public static void main(String args[])
{
String s1="amisha";
String s2="amisha";
if(s1==s2)
{
System.out.println("same");
}
else
{
System.out.println("different");
}
}
}

in java string is an object. so when i evaluate if(s1==s2) , the test condition is evaluated as false. because both string object refers to different memory location even if contents are same. so output of this program should be different but when i run this progarm , output is same.

please tell me how this works ?
+Pie Number of slices to send: Send
When you create a String literal it automatically goes into the String pool. Whenever you create another reference to the same literal it refers to the String already in the pool. A new String object is not created.
+Pie Number of slices to send: Send
See Corey McGlone's article, "Strings, Literally."
+Pie Number of slices to send: Send
I AM MIGHTY! Especially when I hold this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 758 times.
Similar Threads
how many String objects are created
Behaviour of String and StringBuffer class.
scjp ( == vs .equals() )
How many Objects?
doubt in using String
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 12:52:56.