This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by Ernesto Leyva: ...what's the reason I should do this, if the first one work...
Well, if the first one will work...
But it's not always obvious that this is the case. See Strings Literally. To be certain of the comparison, and to make the intent of your code clear to others, it's better to use equals when comparing Strings.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
if (x!=null && x=="abc") System.out.print("Hello World!");
what's the reason I should do this, if the first one work.
if (x!=null && x.equals("abc")) System.out.print("Hello World!");
So I think the question is: Why use .equals() if == works?
Here's the short: The == operator returns true if the references on either side refer to the same object. It's known as the identity operator.
The equals() method is known as the equality operator. Lets say we Dogs, same breed, same name, height, weight, color, etc - our program might say those dogs are equal - but they are definately different dogs, so the identity operator would say they are different - the equals method would say they are the same.
The reason it works for String's is due to the way Strings are placed in the constants pool (Interning) - see Strings Literally as Mark Weber has suggested. The short summary is that most strings that can be determined at compile time will be placed in memory, and whenever you attempt to instantiate another String that's equal to one in the String pool, you'll be given a reference to the one that already exists.