Possible Duplicate:
why equals() method when we have == operator?
When I tried executing the code in Java, it gave me 2 different outputs
String txt1="Hello";
String txt2="Hello";
System.out.println((boolean)txt1==txt2);
String txt1=new String("Hello");
String txt2=new String("Hello");
System.out.println((boolean)txt1==txt2);
Strings are objects. == compares object references, not the content of the strings. To do that, use the String#equals method.
In your first example, txt1 and txt2 are two variables pointing to the same String object. So they're == to each other.
In your second example, txt1 and txt2 are pointing to two different String objects (which have the same sequence of characters), and so they aren't == to each other.
Separately: There's almost never any point to writing new String("string literal"). If you don't know specifically a really, really good reason to do it, don't. There are only a couple of very, very, very unusual situations where you might do that, which relate to interacting with low-level stuff. Not in normal, portable Java code.
There is occasionally a reason to use new String(String) (not a string literal, but an instance you got from somewhere else, like substring). See this article for more on that (thanks Rp-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With