2.12. Boolean Variables

Variables of type boolean can have only one of two values, true or false. The values true and false are boolean literals. The boolean type is named after the mathematician George Boole, who invented Boolean algebra, and variables of this type are described as boolean variables. You can define a variable of type boolean called state with the following statement:

boolean state = true;

This statement also initializes the variable state with the value true.

You can also set the value of a boolean variable in an assignment statement. For example, the statement

state = false;

sets the value of the variable state to false.

At this point you can't do much with a boolean variable, other than to set its value to true or false, but as you will see in the next chapter, boolean variables become much more useful in the context of decision-making in a program, particularly when we can use expressions that produce a result of type boolean.

Several operators combine boolean values, including operators for boolean AND, boolean OR, and boolean negation (these are &&, ||, and !, respectively), as well as comparison operators that produce a boolean result. Rather than go into these here in the abstract, I will defer discussion until the next chapter, where I will also explain how you can apply them in practice to alter the sequence of execution in a program.

NOTE

Note that variables of type boolean differ from the other primitive data types in that they cannot be cast to any ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.