Computer Programming I Instructor: Greg ShawCOP 2210 Primitive Type booleanThe boolean type is named for George Boole (1815-1864), a Britishmathematician who was a pioneer in the study of logic. In his book,The Mathematical Analysis of Logic, Boole created a system of algebrawhich quantified human logical reasoning. Boole’s algebra has only twovalues – 0 and 1 – and is the basis for the modern digital computer. I. Boolean Literals- There are only two values of type boolean, false and true- These are not strings or variables but literals of type boolean,just as 37 is a literal of type int - If this code is executed:int x = 13 ;System.out.println(x > 0) ;the output will be: trueII. Boolean VariablesBoolean variables store a value of true or false and are declaredjust like a variable of any other type, with or without initialvaluesboolean eligible ;boolean done = false ;III. Boolean Assignment Statements- A boolean assignment statement assigns a value of true or falseto a boolean variable, e.g.eligible = age >= 18 && age <= 35 ;- Note that this has the exact same effect asif (age >= 18 && age <= 35) eligible = true ;elseeligible = false ;but is considerably more elegant!IV. Using boolean Variables as Program “Flags”- Once a value has been stored in a boolean variable, the variablemay be used as a program “flag,” in the sense of a signal flag,which tells us to do something if the flag is up (true) or not doit – or maybe do something else - if the flag is down (false)- Examplesif (! done) // pronounced, “if not done”{statements} if (eligible){statements ;}else{other statements ;}V. Why boolean Variables?1. They make the program more “English-like” 2. They provide more efficient evaluation (only 1 bit needs to bechecked) Compare if (eligible)vs. if (age >= 18 && age <= 35)VI. Don’t be Afraid!Some people don’t trust boolean variables and write expressions likeif (eligible == true) instead of if (eligible) andif (done == false) instead of if (!done) Although these have exactly the same effect, they are inelegantand defeat the purpose of boolean variables (see V., above)VII. Boolean Methods- A boolean method is a method that returns a value of true orfalse- Boolean methods are also known as “predicate methods” becausethey answer a yes/no question For examples of all things boolean – variables, assignments,operators !, &&, and ||, and a boolean method, seeLeapYearTester.javaLeapYearTester2.java has two more examples of boolean
View Full Document