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 = 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 AValue of BResulting Value of A && B true false truefalse
Truth Table for the || (or) Boolean Operator Value of AValue of BResulting Value of A || B true falsetrue falsetrue false
Truth Table for the ^ ( exclusive or) Boolean Operator Value of AValue of BResulting Value of A ^ B true false truefalsetrue falsetrue false
Truth Table for the ! (not) Boolean Operator Value of AResulting Value of !A truefalse 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);