This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Search this forum, and you will find many topics where this has been discussed.
in a nutshell, equals() is a method someone (often YOU) implements to do the comparison you want 99.999% of the time.
== compares the references to see if they point to the same object in memory.
when you call "toString()", you are creating a new object. since you call toString twice, you have two distinct String objects, both with the value of "127". so, == returns false, but .equals() would return true.
Never ascribe to malice that which can be adequately explained by stupidity.
Very good question. Before explaining why, let me remind you, that was not the proper way to post your code! Be sure to use code tags while posting code. Ok..that said..let us dive into our question.. 1. Not just Byte b1 = new Byte("127"); even for new Byte("0") it gives false. 2. Why? Simple! b1.toString() OR toString() methods always throw a String, right? And, when you are calling b1.toString() twice, that means two String objects were created. The == operator checks whether the bits are equal. When comparing objects, == actually compares the references and not what's inside the objects! In your code example, you were checking whether two String objects created were ==(means, referring to same object). Since they are not referring to same object, the comparison resulted in false. 3. To actually check if two objects are equal, use equals()!
Now, I have one question: Normally, Strings are placed on String pool. JVM doesn't creates new Strings but simply refers to the existing ones on the pool. Now, considering the above example code, there should actually be only one String object created right? In that case, the if test should result in true, yeah? Please clarify. Thanks in advance!