April 29, 2012

My if statement ALWAYS returns true, no matter what

Question by user1364363

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?

Answer by Peter Lawrey

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.

Answer by Starx

if (that == true);
              // ^ The extra colon you dont need

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!