Declaring a boolean variable can be done in one of two ways: boolean gameOver; 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; 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 Boolean variables can also be used as if statement conditions. Here are some examples: if(gameOver) System.out.println("Game is over"); 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