the type boolean. boolean expressions and boolean variables the type boolean is a primitive type ...
Post on 20-Dec-2015
220 views
TRANSCRIPT
The Type boolean
Boolean Expressions and Boolean Variables
The type boolean is a primitive type Variables of type boolean and Boolean expressions
can have only values of either true or false. Example:
if (number > 0)
System.out.println(“The number is positive.”);
else
System.out.println(“The number is negative or zero”);
Boolean Expressions and Boolean Variables (cont’d)
A Boolean variable can be given the value of a Boolean expression by using an assignment statement.
Example:
int number = -5;
boolean isPositive;
isPositive = (number > 0);
Boolean Expressions and Boolean Variables (cont’d)
A value can also be assigned in the declaration statement.
boolean isPositive = (number > 0); The previous example can be rewritten as follows:
if (isPositive)System.out.println(“The number
is positive.”);else
System.out.println(“The number is negative or zero”);
Naming Boolean Variables When naming a Boolean variable choose a
statement that will be true when the value of the Boolean expression is true.
Examples:boolean isPositive = (number > 0);
boolean systemsAreOK = (temperature <= 100) && (thrust >= 12000) && (cabinPressure > 30);
boolean lightsOn = true;
Precedence Rules
First: the unary operators +, -, ++, --, and ! Second: the binary arithmetic operators *, /, % Third: the binary arithmetic operators +, - Fourth: the boolean operators <, >, <=, >= Fifth: the boolean operators ==, != Sixth: the boolean operator & Seventh: the boolean operator ^ Eighth: the boolean operator | Ninth: the boolean operator && Tenth: the boolean operator ||
Truth Table for the && (and) Boolean Operator
Value of A Value of B Resulting Value of A && B
true true true
true false false
false true false
false false false
Truth Table for the || (or) Boolean Operator
Value of A Value of B Resulting Value of A || B
true true true
true false true
false true true
false false false
Truth Table for the ^ ( exclusive or) Boolean Operator
Value of A Value of B Resulting Value of A ^ B
true true false
true false true
false true true
false false false
Truth Table for the ! (not) Boolean Operator
Value of A Resulting Value of !A
true false
false true
Input and Output of Boolean Values
The values true and false of the type boolean can be input and output the same way that values of the other primitive types
Example:boolean booleanVar = false;System.out.println(booleanVar);System.out.println(“Enter a boolean
value:”);Scanner keyboard =
new.Scanner(System.in);booleanVar = keyboard.nextBoolean();System.out.println(“You entered “ +
booleanVar);