The Type boolean Boolean Expressions and Boolean Variables
The Type boolean
Boolean Expressions and Boolean Variables o The type boolean is a primitive type o Variables of type boolean and Boolean expressions can have only values of either true or false. o 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) o A Boolean variable can be given the value of a Boolean expression by using an assignment statement. o Example: int number = -5; boolean is. Positive; is. Positive = (number > 0);
Boolean Expressions and Boolean Variables (cont’d) o A value can also be assigned in the declaration statement. boolean is. Positive = (number > 0); o The previous example can be rewritten as follows: if (is. Positive) System. out. println(“The number is positive. ”); else System. out. println(“The number is negative or zero”);
Naming Boolean Variables o When naming a Boolean variable choose a statement that will be true when the value of the Boolean expression is true. o Examples: boolean is. Positive = (number > 0); boolean systems. Are. OK = (temperature <= 100) (thrust >= 12000) (cabin. Pressure > 30); boolean lights. On = true; && &&
Precedence Rules o o o o o 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 false true false
Truth Table for the || (or) Boolean Operator Value of A Value of B Resulting Value of A || B true true false false
Truth Table for the ^ ( exclusive or) Boolean Operator Value of A Value of B Resulting Value of A^B true false true false
Truth Table for the ! (not) Boolean Operator Value of A Resulting Value of !A true false true
Input and Output of Boolean Values o The values true and false of the type boolean can be input and output the same way that values of the other primitive types o Example: boolean. Var = false; System. out. println(boolean. Var); System. out. println(“Enter a boolean value: ”); Scanner keyboard = new. Scanner(System. in); boolean. Var = keyboard. next. Boolean(); System. out. println(“You entered “ + boolean. Var);
- Slides: 11