rickygrimes rickygrimes - 1 year ago 124
Java Question

if(boolean condition) in Java

This is always very confusing to me. Can someone please explain it? The confusion I have is - boolean default to false. So in the below example, does it enter the if loop when state is not turned on ie it is TURNED OFF if(condition is false) OR does it enter the if loop when state is TURNED ON, in other words if(condition is true)

boolean turnedOn;
//do stuff when the condition is false or true?
//do else of if

I know this is a very basic question, but if you could explain the answer in very basic language, that would be great :) Feel free to point me to duplicate posts that have a very good explanation (I did not find one where I could clearly get it). Also feel free to change the subject of the post if you'd like to make it more generic.

Answer Source

Okay, so..

// As you already stated, you know that a boolean defaults to false.
boolean turnedOn;
if(turnedOn) // Here, you are saying "if turnedOn (is true, that's implicit)
//then do this
else // if it is NOT true (it is false)
//do this

Does it make more sense now?

The if statement will evaluate whatever code you put in it that returns a boolean value, and if the evaluation returns true, you enter the first block. Else (if the value is not true, it will be false, because a boolean can either be true or false) it will enter the - yep, you guessed it - the else {} block.

A more verbose example.

If I am asked "are you hungry?", the simple answer is yes (true). or no (false).

boolean isHungry = true; // I am always hungry dammit.
if(isHungry) { // Yes, I am hungry.
   // Well, you should go grab a bite to eat then!
} else { // No, not really.
   // Ah, good for you. More food for me!

   // As if this would ever happen - bad example, sorry. ;)