CS115 lecture notes, Spring 1999 Week 5, Friday Quiz 7. The quiz program is way more verbose than it needs to be. Booleans -------- Named after Boole, who invented an algebra (Boolean algebra) that is based entirely on two values, sometimes called 0 and 1, true and false, or high and low. Since computers are based on a binary number system, there is a natural connection between computing and Boolean algebra. In Java: 1) the result of a comparison is a boolean value. 2) you can assign the result of a comparison to a boolean variable. public static boolean isFrabjuous (int x) { boolean frabjuousFlag = (x > 0); return frabjuousFlag; } 3) a boolean method can return the result of a comparison directly! public static boolean isFrabjuous (int x) { return (x > 0); } This makes it really obvious that isFrabjuous is just testing for positive numbers. 4) You can use any boolean expression as a condition inside an if statement, and that includes invoking methods that return boolean. if (isFrabjuous (x) && isHoopy (x)) { println ("x is hoopy and frabjuous"); } 5) The logical AND operator (denoted &&) in Java, is true only if both operands are true. The logical OR operator (||) is true if either operand is true, and also true if both are. The logical NOT operator (!) operates on a single operand. The result is the opposite of the operand. ! is pronounced BANG. 6) WARNING: there are also operators denoted & and | that operate on both booleans and integers. On booleans, they do the same thing as && and ||. What they do to integers is too horrible to speak. Overloading ----------- You can have more than one method with the same name, as long as they take different arguments. When you invoke an overloaded method, the compiler knows which version you want to invoke by looking at the types of the arguments. As always, the compiler can always tell the type of an expression. Overloaded methods can have different return types. Example: Math.abs, Math.min, Math.max are all defined for both int and double. In each case, the return value is the same type as the arguments. Other example: print and println are overloaded. There is a version that accepts a single int, another version that accepts a single double. Same for String and boolean. Overloading is a useful feature, but it can make code hard to read because it is not always clear what method is getting invoked.