True and False in Java – Working With Booleans

In java true and false conditions are know as booleans. Conditions are where you need to make a choice between a positive condition and a negative condition and the data type used for that in java is the boolean primitive and we also have a Boolean class.

In computers and software we often want to make decisions and control the flow of programs. We want to control the flow based on a condition and every condition should have a positive and negative result. For example if we are checking if a door is open, it’s either closed or open, so if we ask the question “is the door open”, the answer is either true of false.

The boolean data type therefore only has two values, true and false. So when we need to evaluate any condition in java, each part of the condition will evaluate to true or false, and the overall condition will evaluate to either true or false too. 

If we want to setup a boolean variable on java we may well define something similar to the below:

So we are setting our boolean variable to a value of true. We can then use this variable in a condition similar to the below

We can use the IF statement to check the condition and then change the flow of the logic depending on whether evaluating the condition gives a true or false result. When the condition evaluates to true the block of code following the IF will be executed. If an ELSE is specified as we have here  and the condition evaluates to false, then the block of code following the else will be executed.

The condition only needs to evaluate to true or false so we can abbreviate the IF statement above to simply checking the state of the variable. The code below is the same as what we had previously.

The IF statement checks for a positive boolean result. If we wanted to check for a negative boolean result we can use the NOT operator to achieve this. The NOT operator in java is the exclamation mark. This allows us to check for the opposite state, so that a negative condition will the cause the IF block to be executed and a positive condition will trigger the ELSE block. 

Leave a Comment

Your email address will not be published. Required fields are marked *