tags:

views:

58

answers:

2
String s1 = "Amit";                 //true
String s2 = "Amit";                 //true
String s3 = new String("abcd");     //true
String s4 = new String("abcd");     //false
System.out.println(s1.equals(s2));  //true
System.out.println((s1==s2));       //true
System.out.println(s3.equals(s4));  //false
System.out.println((s3==s4));       //false

Assume it to be in main why the output of the above code is

true true true false and not true true false false???

+2  A: 

I'm not going to answer your question directly as it seems to be homework, but what you are looking for is this:

==, .equals(), compareTo(), and compare()

The link above discusses string contents equality and string reference equality. This is what your question is in essence and it gives a great way of explaining the concepts.

Kyle Rozendo
sorry I realize it now.. its == at fourth and not third.
terrific
+3  A: 

Java uses a "string literal pool." Since strings are immutable objects, there's no reason two strings initialized to the same literal can't be the same object—and as your code output suggests, they are the same object. (s1 and s2 are two names for the same location in memory)

The reason this isn't true for s3 and s4 is because you're explicitly allocating new strings, and using the constructor to initialize them. This means they are different objects, and hence they fail the "==" test.

In other words,

== compares if two object references are equal

.equals() compares if the contents of two objects are equal, irrespective of where they are in memory.

Kevin Griffin
@Kevin - -facepalm-
Kyle Rozendo
@Kyle Ah, yeah, it does seem like homework, doesn't it? My bad. But as long as he learns the concept, right?
Kevin Griffin
thanks a ton !!!m novice to this.. learning everyday..
terrific
Hehehe yea Kevin, that's why I threw in the link with the info :)
Kyle Rozendo