AP Computer Science Java: Lesson 2.7
Conditional Statements - Boolean Variables


Lesson 2.7 - Boolean Variables

Purpose: To learn how to define and work with boolean variables

True or False? 
George Boole was a British mathematician and philosopher in the 1800's who is credited with defining an Algebraic form of logic which is now known as Boolean Algebra. This system of logic is one of the building blocks of computer science. In fact, one of Java's primitive data types is called boolean. A boolean variable is one that is capable of taking only one of two values, true or false. Boolean variables are typically used to take the place of conditions and to make statements more readable.

Declaring a boolean variable can be done in one of two ways:

   boolean gameOver;
   boolean gameOver = false; // or true

In the first declaration, gameOver has no initial value. In the second, it is initialized with the value false. A boolean variable can also be initialized to true.

Assigning a value to a boolean variable is acheived by assigning a condition like those that appear in the parentheses of an if statement. Here are several examples (assume that all assigned variables are declared boolean):

   gameOver = score==10;
   busted = points>21;
   accepted = age>=16 && gpa>3.00;
   gameOver = score1==10 || score2==10;

Note that the right-hand side of each assignment statement is an expression that must evaluate to true or false. These are called boolean expressions and will be discussed at length in the next lesson. The following pair of assignment statements are incorrect:

   gameOver = 10; //doesn't assign true or false
   busted = points=22; //doesn't have two equal signs

Boolean variables can also be used as if statement conditions. Here are some examples:

   if(gameOver) System.out.println("Game is over");
   if(busted) balance = balance - bet;
   if(accepted) System.out.println("You are accepted!");

It is also possible, but redundant, to write an if with a boolean variable condition as follows:

   if(gameOver==true) System.out.println("Game is over");

The use of ==true still works, but is not necessary. Either way, if the boolean variable is true, the statement engages. if it is false, it doesn't.

In closing, boolean variables are not needed that often, but do prove useful in certain situations that will come about in future discussions, such as looping. Stay tuned...


© DanShuster.com