Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String references in java [duplicate]

Tags:

java

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"...?

like image 294
user1709584 Avatar asked Sep 30 '12 09:09

user1709584


1 Answers

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.

like image 128
Marko Topolnik Avatar answered Sep 21 '22 04:09

Marko Topolnik