|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
The type boolean is much simpler than (say) int, because rather than 4+ billion ints, there are only two boolean values: true, and false. Note that these two names aren't variables; they're values, just like 17 and -34 are.
There are some functions in Java which take two numbers, and return a boolean. ==, >, >=, ==, !=, etc.. Type the following boolean expressions into BlueJ's Code Pad:
(2+2 == 4) 2+2 == 5 2+2 != 5 2+2 != 4 // "Is it true, that 2+2 is not four?" 5 > 4 5 > 99 5 > 5 5 >= 5 double x = 5; double y = 43.2; (x+y)/2 >= Math.sqrt(x*y) // is the arith.avg less than geom.avg., for the current value of x,y? jo.wedPizzaArea(20) > jo.tuePizzaArea(20) // true or false? |
There is only one built-in Java statement which really uses booleans: that's the if-else statement1. Syntax:
if (condition) { statements… } else { statements… } |
Hint: The two types of statements we're concerned with are either a return statement, or initializing a variable.
Practice:
Write a function myMax which takes in two numbers,
and returns the bigger.
(What should be returned, if the two inputs are equal?)
As always, remember the
steps of the design recipe.
Example: Write a program for the following:
/** Given how many slices of (say) mushroom pizza are * currently available, create a nice tempting message * to advertise (shout out, or post, or put on a * LED sign...) * * @param topping The type of pizza (e.g. "pepperoni") * @param slicesReady The number of currently ready-to-serve * slices with the given topping. * @return A complete sentence describing the inventory. * For example: * inventoryMessage( "mushroom", 3 ) * = "There are 3 piping hot slices of mushroom pizza, ready to eat!" * inventoryMessage( __________, __ ) * = ______________________________________________ * inventoryMessage( __________, __ ) * = ______________________________________________ */ |
String slicesReadyMsg( String topping, int slicesReady ) { if (slicesReady == 1) { return "There is " + slicesReady + " piping hot slice of " + topping + " pizza, ready to eat!"; } else { // slicesReady isn't equal to 1 return "There are " + slicesReady + " piping hot slices of " + topping + " pizza, ready to eat!"; } } |
We can do better: Where do the two solutions differ? In only two places: “is” vs. “are”, and the suffix “s” vs. no suffix at all. We can factor out the common code, and let our if statement focus on just those differences:
/* (Same comments as before; omitted for lecture presentation) */ String slicesReadyMsg( String topping, int slicesReady ) { String verbForm; // The correct verb for our result. String plurality; // The noun-suffix, correctly plural or singular. // We just declared two local variables; now initialize them: if (slicesReady == 1) { verbForm = "is"; plurality = ""; } else { verbForm = "are"; plurality = "s"; } return "There " + verbForm + " " + slicesReady + + " piping hot " + ("slice" + plurality) + " of " + topping + " pizza, ready to eat!"; } |
We used to have a rule that immediately after declaring a variable, you should initialize it. We still have that rule! Sometimes it's an if-else statement which is doing the initialization, but that's fine. Just be careful:
Guideline:
- When using an if-else statement for initializing a variable, make sure both branches of the if-else statment initialize that variable.
- Likewise, when using an if statement to return an answer, make sure both branches of the if-else statement returns an answer.
Similarly, if you have a return inside a
branch of an if statement,
consider writing your code so that every
branch of the if statement has a return.
This rule is less important; because it's clear that the first branch
without a return essentially starts an else
block which lasts for the rest of the function.
/** Give an estimate of how far it will take to travel a given distance, on the highway. * @param miles How far to travel, in miles. * @param isRoadClear Is the road in good condition (true), or is it icy/foggy/accidented (false)? * @return The estimated time of driving that far, in hours. * highwayDrivingTime( 0, true ) = 0 * highwayDrivingTime( 0, false ) = 0 * highwayDrivingTime( 65, true ) = 1.0 * highwayDrivingTime( 65, false ) = 1.6 * highwayDrivingTime( 130, true ) = 2.0 * highwayDrivingTime( 130, false ) = 3.2 */ double highwayDrivingTime( double miles, boolean isRoadClear ) { int SPEED_LIMIT = 65; // posted limit, in MPH. (We can declare and initialize, all on one line.) double DELAY_FACTOR = 1.60; // If road isn't clear, how much does that slow us down? // 2.0 means twice as long, 1.0 is no slowdown (and less than 1.0 would be a speedup). if (isRoadClear) { return (miles / SPEED_LIMIT); } else { return (miles / SPEED_LIMIT) * DELAY_FACTOR; } } |
We can also return a true/false answer from a function:
/** * @param age The age (in years) of the person in question. E.g., 18months is age 1. * @return whether or not the person must register with Selective Service. * mustRegisterForDraft(22) == true * mustRegisterForDraft(14) == false */ boolean mustRegisterForDraft( int age ) { return (age >= 18); } |
if (age >= 18) { return true; } else { return false; } |
By the way, is this a silly function to write? Why, anybody who wants to call this function could more simply write the comparison against 18 directly. So what do we gain, by writing this as a separate function? We'll revisit this function soon.
A function which returns a boolean value is called a predicate function (or just, “predicate”). Often, predicates' names start with “is” or “has”: For example “isHappy”, “hasEaten”, etc.. So if these names happened to be methods for PizzaServer, our code might naturally have lines like
if (jo.hasEatenSince( 2007, 09, 01 )) { return "I am stuffed!" } else { return "Is anybody else hungry?"; } |
1We'll talk about the while statement in a few weeks. ↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2008, Ian Barland, Radford University Last modified 2008.Jan.24 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |