I am a programmer and the 2 things you rely on the most are that the computer will do exactly what you tell it, good or bad and that your debugger will tell you what is happening in your code when debugging it. Today both of those failed when I was writing some code in Java.
The one thing we all do is use booleans and make forks in software execution using if statements. So when one was not working correctly I was trying to debug it by using the Eclipse debugger. In the debugger I was not just stepping through the code but was looking at the value of variables and the results of the statement in the if statement. The debugger was telling me the value was false but the if statement was transferring control into the the code inside.
It turned out the issue was not that complicated. Two Booleans being compared to each other.
Boolean A = new Boolean(true);
Boolean B = new Boolean(true);
Eclipse debugger was saying that A!=B = false but Java executed the println which showed that Java thought it was true that A was not equal B. If I changed the code to define the Booleans as either primitives or in the form Boolean A = true; it worked as expected. But there are two things wrong here.
One, Java is right that A!=B in the first case because you are comparing two objects not their values. A is not the same object as B. But Eclipse Debugger said they were equal which is wrong and that was the first thing that got me looking at this. When you change the way you created the two Boolean objects to not use the new constructor you are actually pointing both A and B at the same object and when you compare them you get true only because they are the same object. If you use the primitive it them actually compares the values.
But there is more going on here. I tried a bunch of things and it gets murky. If you compare the original A to true such as (A==true) it works, comparing the value of A to the value true. And if you use (A&&B) that also works by checking both values. Only in the case of (A==B) and (A!=B) does it not use the values of the Boolean objects and use the actual objects themselves.
So if you have to use the Boolean class and have to check if they are equal use the .equals() method of the boolean class. Hopefully Eclipse will fix their debugger to check if what is being compared is the objects and not the values.
- Adventures in Java: 1 (echlinm.wordpress.com)
- What are Debugging tools and what are they used for in Java language (wiki.answers.com)