The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Boolean Expressions

Most of the operations we have seen produce results that are the same type as their operands. For example, the + operator takes two ints and produces an int, or two doubles and produces a double, etc.

The exceptions we have seen are the relational operators, which compare ints and floats and return either true or false. true and false are special values in Java, and together they make up a type called boolean. You might recall that when I defined a type, I said it was a set of values. In the case of ints, doubles and Strings, those sets are pretty big. For booleans, not so big.

Boolean expressions and variables work just like other types of expressions and variables:

    boolean fred;
    fred = true;
    boolean testResult = false;

The first example is a simple variable declaration; the second example is an assignment, and the third example is a combination of a declaration and as assignment, sometimes called an initialization. The values true and false are keywords in Java, so they may appear in a different color, depending on your development environment.

As I mentioned, the result of a conditional operator is a boolean, so you can store the result of a comparison in a variable:

    boolean evenFlag = (n%2 == 0);     // true if n is even
    boolean positiveFlag = (x > 0);    // true if x is positive

and then use it as part of a conditional statement later:

    if (evenFlag) {
      System.out.println ("n was even when I checked it");

A variable used in this way is frequently called a flag, since it flags the presence or absence of some condition.

Last Update: 2011-01-24