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 Methods

Methods can return boolean values just like any other type, which is often convenient for hiding complicated tests inside methods. For example:

  public static boolean isSingleDigit (int x) {
    if (x >= 0 && x < 10) {
      return true;
    } else {
      return false;
    }
  }

The name of this method is isSingleDigit. It is common to give boolean methods names that sound like yes/no questions. The return type is boolean, which means that every return statement has to provide a boolean expression.

The code itself is straightforward, although it is a bit longer than it needs to be. Remember that the expression x >= 0 && x < 10 has type boolean, so there is nothing wrong with returning it directly, and avoiding the if statement altogether:

  public static boolean isSingleDigit (int x) {
    return (x >= 0 && x < 10);
  }

In main you can invoke this method in the usual ways:

  boolean bigFlag = !isSingleDigit (17);
  System.out.println (isSingleDigit (2));

The first line assigns the value true to bigFlag only if 17 is not a single-digit number. The second line prints true because 2 is a single-digit number. Yes, println is overloaded to handle booleans, too.

The most common use of boolean methods is inside conditional statements

    if (isSingleDigit (x)) {
      System.out.println ("x is little");
    } else {
      System.out.println ("x is big");
    }


Last Update: 2011-01-24