Possible Duplicate:
String comparison and String interning in Java
I try to run the following code in java:
if("hello".trim() == "hello".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");
and it prints Equal. I understand in this case both strings have same reference. But When I try the same by just adding a space in both strings, it prints "Not Equal".
if("hello ".trim() == "hello ".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");
Can anyone explain why I am getting "Not Equal"...?
Just check out the implementation of trim
and it will be clear to you. If trim
determines that the string has no leading/trailing whitespace, it returns the same string—that's your first case. In the second case a new string is created, so you have two equal String instances, each with its own identity. And, as I think you are aware, the operator == compares references and not objects, so it doesn't care whether the two instances represent equal strings or not.
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