Reputation: 49
This just is't making sense to me at all.
This is my code:
boolean that = false;
if (that == true);
{
System.out.println("That is " + that);
}
And yet it will print the line even though my output is
That is false
I'm doing this in java and I'm using Eclipse galileo, so each time I compile/run my program it saves it so the compiler should be getting updated version of my program. What's going on?
Upvotes: 2
Views: 3041
Reputation: 533442
A common mistake. Remove the ;
at the end of the if
statement.
BTW I always write the following if I use brackets and I use the code formatter of the IDE.
if (that == true) {
System.out.println("That is " + that);
}
This means if you have a mis-placed ;
or {
it can be more obvious.
Upvotes: 8
Reputation: 12484
It's because of the semicolon you have here:
if (that == true);
Remove that semicolon ! It causes the code to do nothing after checking the conditional (that == true)
- technically it's an "empty statement" - i.e. we can have a loop like so:
for (int i = 0; ; i++){
System.out.println("Thanks" );
}
And it would go forever!
Upvotes: 3
Reputation: 4444
Remove the ;
boolean that = false;
if (that == true)
{
System.out.println("That is " + that);
}
otherwise the print is always executed.
Upvotes: 3
Reputation: 308733
Try it like this:
boolean that = false;
if (that)
{
System.out.println("That is " + that);
}
Notice the extra semi-colon after the if
in your code? That's why.
The logical test is closed by the semi-colon, then the next block is always executed.
If you remove the semi-colon it'll match your intuition.
Upvotes: 2