Home > Articles

  • Print
  • + Share This

The boolean Primitive

The simplest data type available to you in Java is the primitive type boolean. A boolean variable has only two possible values, true or false, which are represented with reserved words. In some other languages, Boolean types take on values of 0 or 1; or, as in C/C++, 0 represents false and all other numbers are interpreted as true. Java treats boolean in a strict and type-safe manner by tightly restricting its allowed values. A boolean can never be treated as an integer or vice versa.

boolean variables are often used when you want to keep track of the state of a simple object attribute. For instance, if you are writing a flight scheduling application, whether a given flight is on time is important to you. You might declare a variable like this:

boolean onTime = true;

In Chapter 6, "Control Flow," you see how boolean variables can be used to direct the behavior of a program. For instance, if a flight is on time, your program proceeds normally, but if a flight is late, it sends a message to the departure gate for each connecting flight to alert someone that passengers will be arriving late.

You can change the value of a boolean variable in several ways. The first way to do this is explicitly. For instance, you can change the onTime status of flight by typing

onTime = false;

You can also assign the value of one boolean variable to another:

onTime = arrivedOnSchedule;

This only works if arrivedOnSchedule is also declared as a boolean (it's a compiler error otherwise). If so, onTime will only be assigned a value of true or false because those are the only values possible for arrivedOnSchedule.

The previous two examples changed the value of onTime using a boolean literal and another boolean variable. Although you are now familiar with variables, you might wonder what a literal is. A literal is a source-code representation of a value, in this case, the value false.

The main point is that the right side of an assignment statement for a boolean variable must evaluate to a boolean. In addition to using a single value or variable, you can also write logical expressions that meet this criterion. For instance, the following line would update onTime based on the supporting times:

onTime = (estimatedArrivalTime <= scheduledArrivalTime);

The equation on the right will evaluate to either true or false depending on the specific time values. You learn more about this type of equation later in Chapter 6.


Note - Boolean types are a feature in Java not found in languages such as C. To some, this stricter adherence to typing might seem oppressive. However, the ambiguity and potential typecasting abuses that it prevents are well in line with the goals of making Java a safer and more reliable language.


  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.