Originally posted by yogesh srinivasan:
in the main function
static public void main(String[] args)
{
String a="hai";
String b="hai";
String c=new String("ram");
String d=new String("ram");
System.out.println(a==b);
System.out.println(c==d);
}
output is
true
false
why the output c==d is not returned as true ?? how does the delaration changes their natuure to == operation ??
In the first case, both references point to the same object in memory (in the string pool). This is decided at compile time to save memory.
In the second case, when constructing an object using new, a new object will always be created. Hence the references point to different objects.
Remember that "==" will compare only the reference to the object, not the contents of the object (for which you can use the equals() method).