Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string related question

 
Amisha Shah
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See Corey McGlone's article, "Strings, Literally."
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic