Saturday, January 31, 2009

How to use If() for Experts

I just had a really funny problem in Java:

String name1 = "something";
String name 2 = "somethingelse";
if(name1.equals(name2))
{
result = true;
}
if(result = true)System.out.println(true);

Guess the output (in the Java Console). It was: true
yes that's right: true

How could the output be true if the two Strings are so different. "something" is definitely not equal to "somethingelse". I even used .equal to compare the two Strings like I learned from previous mistakes.

Well after like an hour of searching I found my stupid mistake:
if(result = true)System.out.println(true);
The single equal sign assigned the value true to result.
I should have typed:
if(result == true)System.out.println(true);
To make it a comparison.

Don't ask me how Eclipse didn't catch that mistake...

4 comments:

Peter Stuifzand said...

But of course you should never use an if-statement like that. If does an == true, implicitly. Writing the if statement the way you do it will make it look like this:

(result == true) == true

If you write it as 'if (result)', you will never have the 'not enough equal-signs' problem.

Simon Gruening said...

Yeah, I figure so too later on (when I was working on some other things using If statements). Just some stupidities I do when I'm not concentrating =D

Peter Stuifzand said...

The same thing happens when I read code I've written a few months earlier. It's probably a sign that we got better at writing code.

Anonymous said...

Be careful with primitive data types vs. object data types. int i =7 vs. String name = "Java", if you actually peek in the memory location for i you will find the binary representation of 7 but for name you find a memory address pointing to the actual value of name. This causes problems with == vs. .equals("a value"). == compares the values at the memory location irrespective of whether it is a real value of a memory value.