If statement using return boolean

This page explains Java if-statements and boolean expressions with example code and exercises. See also the associated CodingBat live boolean logic practice problems to practice boolean logic code or study for an exam. Written by Nick Parlante.

If Statement

For a program to do anything interesting, it needs if-statements and booleans to control which bits of code to execute. Here is a simple if-statement:

if (temperature > 100)

The simplest if-statement has two parts -- a boolean "test" within parentheses ( ) followed by "body" block of statements within curly braces < >. The test can be any expression that evaluates to a boolean value -- true or false. The if-statement evaluates the test and then runs the body code only if the test is true. If the test is false, the body is skipped.

If Then Else

Another common form of if-statement adds an "else" clause such as with the code below which prints one message or the other:

if (temperature > 100) < System.out.println("Too darn hot"); >else

The if/else form is handy for either-or logic, where we want to choose one of two possible actions. The if/else is like a fork in the road. Under the control of the boolean test, one or the other will be taken, but not both. For example, the famous Robert Frost poem is a thinly disguised comment on the importance of the if/else structure:

Two roads diverged in a wood, and I - I took the one less traveled by, And that has made all the difference.

Java Comparison Operators: , >=

No: 10 < X < 20

It's tempting to write an expression like "10 < X < 20" to see if X is between 10 and 20. That does not work. Each " =, etc.. with primitives like int. Use .equals() with objects like String and Color. Since the dereference dot (.) only works with objects, you can remember it this way: if it can take a dot then use .equals() (e.g. a String), otherwise use == (e.g. an int).

It is also possible to use == with objects. In that case, what == does is test if two pointers point to exactly the same object. Such as use of == is a little rare in Java code, and so it's simpler to concentrate on using equals() with objects, and == only with primitives.

Boolean Type

The simplest and most common form of boolean expression is the use a = 5) is true. (We could equivalently write the if-statement with (score >= 5), but the point was to demonstrate the !).

Boolean Restaurant Example

Suppose you want to get a table at a hip restaurant, but we are afraid that the Maitre'd is going to say something rude instead of seating you. The variable "style" represents the stylishness of your clothes and the variable "bribe" represents the bribe presented to the Maitre'd. The Maitre'd is satisfied if style is 8 or more and bribe is 5 or more. The Matire'd says "Je n'think so" if they are not satisfied. One way to code this up is to write the "satisfied" expression as a straight translation of the problem statement, and then put a ! in front of it:

// Say something mean if not satisfied if (! ((style>=8) && (bribe>=5)) )

With combinations of !, =, etc. there can be a few different ways to code what amounts to the same thing. As a matter of style, we prefer the code that reads most naturally to express the goal of the code. For example, the following is equivalent to the above, although I find it near impossible to decipher:

// Say something mean if not satisfied if (!(!(style<8) && !(bribe<5))) < .
Here is another equivalent form, which is not so bad.
// Say something mean if not satisfied if ((style<8) || (bribe<5)) <.

Java also has "bitwise" operators & and | (more rarely used) which are different from && and ||. If your boolean code will not compile, make sure you did not accidentally type a bitwise operator (&) instead of a boolean operator (&&).

Boolean Precedence

The above examples use parentheses to spell out the order of operations. The boolean not ! has a high precedence -- in (!a && b) the ! is evaluated on the a, before the &&. We could add in parenthesis (!(a && b)) to force the && to evaluate before the !. The && operator is higher precedence than ||, so in (a || b && c), the && happens first. There are parallels between the boolean operators and arithmetic: ! is like unary -, && is like *, || is like +. The comparison operators ( = and &&. Remember that all the unary operators, such as !, have a high precedence. To evaluate something before the !, we frequently need to put the something in parentheses like this: !(something). For example:

if (! i < 10 ) < . // NO does not work

The precedence of the ! is too high, it wants to execute before the = 100). You might think that the opposite of , but it is not. The opposite of =, and the opposite of > is = 50) line, we know that (score >= 200) must have been false, and so the score is 199 or less.

Using Booleans Directly

Suppose you want an if-statement to check if a "num" variable is 3 like this:
// suppose num is an int if (num == 3) < .

That code works fine. Suppose instead that you have a boolean variable "isSummer" and you want an if-statement that runs if isSummer is true. Here is one way to write that code:

if (isSummer == true) < .

That code works ok, but it is a little longer than necessary. It also has a problem if you accidentally type a single "=" instead of "= =" looks reasonable. A shorter way to write the code, and a good defense against the above bug is to use the boolean variable directly without "= is" or "has". For example, a Car object might implement an isOutOfGas() method which returns true if the car is out of gas or false otherwise. In general, the client can use boolean messages to check for various true/false conditions of the receiver. For example a Bear class might have an isMother() method which is true if the bear is a mother, and a hasCubs() method which is true if the bear has cubs with it:

public class Bear < . // Returns true if the bear is a mother bear public boolean isMother() < . // Returns true if the bear has cubs with it public boolean hasCubs()

Now suppose we are writing the meetBear() code for a Backpacker, used when the Backpacker meets a bear in the woods:

// Code for when we meet a bear in the woods void meetBear(Bear bear) < System.out.println("Oh look, a bear."); if (bear.isMother()) < System.out.println("Hi mom!"); >if (bear.hasCubs()) < System.out.println("Hi cute little bears!"); >if (bear.isMother() && bear.hasCubs()) < System.out.println("Oh @#$@#$!, Run!"); >>
Another way to write the mother if-statement uses "== true" like this: if (bear.isMother() == true)

That code will work fine, but it is not the best style. The "== true" adds nothing, since the if-statement itself already checks if the test is true. Therefore, it is better to write it the direct way:

if (bear.isMother())

Writing a Boolean Method

Writing a method that returns a boolean is just like writing any method that returns value, but ultimately we are just returning either true or false. For example, suppose we are writing code for a hybrid-electric car. The car class as instance variables that track the amount of gasoline and battery charge: myGasoline (in the range 0..100), and myBatteries (also 0..100). Suppose the Car class implements an isLow() message that returns true if the car is low on fuels. It returns true if the sum of the gasoline level and the battery level is less than 10. The isLow() message is used by the dashboard to decide to light the "low fuel" light. What does the code for isLow() look like? Here is one way to write it:

public class Car < private int myGasoline; private int myBattery; . // Returns true if we are low on fuels public boolean isLow() < if ((myGasoline + myBattery) < 10) < return true; >else < return false; >> >

The above code will work fine. It has a boolean test checking for low fuels, and depending on that it runs either "return true;" or "return false;". But there is a better way. We can cut out the if-statement middle-man. Notice that the boolean in the if-test (true or false) happens to be the same as the value we want to return. If the test value is true, we return true. If the test value is false, we return false. So you can just return the test value directly! In the short version below, we compute the desired boolean value with the expression "((myGasoline+myBattery) < 10)", and just return that value (which at runtime will either be the value true or the value false, depending on the gasoline and battery levels):

public boolean isLow() < // Compute (true or false) if we are low, // and return that boolean value directly. return ((myGasoline + myBattery)

Writing the method the long way is not terrible style (i.e. we won't mark off for it!), but it's nice to be comfortable enough with boolean values to write it the short way.

Boolean Logic Examples

Code examples that demonstrate boolean code.
/* * Do we go on a second date with someone? * The given chemistry is in the range 0..100 and isSchool * is true if it is during the school year. The answer is yes if chemistry is * 60 or more, or 40 or more not in the school year. */ public void secondDate(int chemistry, boolean isSchool) < if (chemistry>=60 || (!isSchool && chemistry>=40)) < System.out.println("Sure!"); >else < System.out.println("I don't want to spoil our friendship"); >> /* * Returns true if the person gets into Stanford. * Given gpa = 0. 4.0, isGates = child of Bill Gates, * isDarth = associated with Darth Vader. * To get in: must not be associated with Darth Vader at all * Gpa must be over 3.95 * Or gpa over 1.0 if child of Bill Gates */ public boolean getIntoStanford(double gpa, boolean isGates, boolean isVader) < if (!isVader && (gpa>=3.95 || (gpa>=1.0 && isGates))) < return true; >else < return false; >> // Variant, where we return the boolean directly public boolean getIntoStanford2(double gpa, boolean isGates, boolean isVader) < return (!isVader && (gpa>=3.95 || (gpa>=1.0 && isGates))); > // Variant, where we use an if-return for the darth case. // I think maybe this one is the best -- the one big expression is // a bit hard to follow, this version makes it more obvious. public boolean getIntoStanford3(double gpa, boolean isGates, boolean isVader) < if (isVader) < // no way, it'a deal killer! return false; >// Otherwise just use gpa and isGates return (gpa>=3.95 || (gpa>=1.0 && isGates)); >

Boolean Puzzles

These are little puzzles based on reading boolean code. I have used questions like these to write CS exams.

// For all values of num and bool. what does this print? public void test1(int num, boolean bool) < if (num >= 90 || !bool) < System.out.println("A"); >else < System.out.println("B"); >> // For all values of num and bool, what does this print? // Note: deciphering this is hard, harder than most // code-writing problems, but it's a good way to // exercise your logic skills. I can only figure it // out by making a little chart of the possible values. public void test2(int num, boolean bool) < if (num >= 90 && bool) < System.out.println("Tic"); >else if (num >= 20) < System.out.println("Tac"); >else < System.out.println("Toe"); >>

Puzzle Answers

test1: bool true false num >=90 A A num < 90 B A test2: bool true false num >= 90 Tic Tac 20

Doubles vs. ==

One odd case of == is that you should not use == or != with doubles, since the intrinsic little error term on every double value throws off the operation of ==. For example, summing up 1/10, 100 times may not exactly == 10.0. To compare two doubles, subtract one from the other, and then see if the difference is very small:

// suppose we have doubles d1 and d2 // We use the Math.abs() standard method that computes // absolute value // check if d1 and d2 are essentially equal // (if the absolute value of their difference is less // than 1e-6 (i.e. 0.000001) if (Math.abs(d1 - d2) 

CodingBat.com code practice. Copyright 2012 Nick Parlante.