Lesson 5.1 The boolean Type
The boolean Primitive Type
In a previous lesson, you learned that Java has four primitive type families: integers, floating-point numbers, characters and booleans. In that lesson you learned quite a bit about each of these families except for the boolean type.
The boolean type holds the two values--true and false. As with the other primitive types, you can have boolean variables and boolean literals. To write the boolean literal values you simply write true or false. Make sure you don't accidentally write True or TRUE; that's not the same thing.
You create a boolean variable the same way you create an int, long, or double variable: you start with the type, select a name, and then [optionally] initialize your variable.
Here are two boolean variables definitions:
boolean empty = true;
boolean visible; |
The same rules apply to boolean variables as apply to integer or floating point variables. If you fail to initialize a boolean field, then the variable is automatically given the value false. If you fail to initialize a boolean local variable, then you must assign a value before using the variable, or Java will refuse to compile your code.
|
Naming boolean Variables
|
When you choose a name for a boolean variable, try to think about how the variable will be used. Try to name your variables so that when the value is true, your conditional expressions can be phrased "naturally" like this:
if (visible) ...
if (finished) ... |
boolean Methods
Many methods produce boolean values, and you can use boolean variables to store the results of calling such methods.
Here are some examples using boolean methods in the AWT:
visible = aLabel.isVisible();
enabled = aButton.isEnabled();
showing = aWindow.isShowing(); |
You can use Java's not operator [!], which you'll look at a little more carefully in Lesson 5.3, "Logicals", to "reverse" the value of a boolean expression. Here's a small example program that shows how this works:
| Switcher.java |
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Switcher extends Applet
implements ActionListener
{
Label aLabel = new Label("Now you see me");
Button switchIt = new Button("Switch It");
public void init()
{
aLabel.setForeground(Color.red);
aLabel.setBackground(Color.yellow);
add(aLabel);
add(switchIt);
switchIt.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
boolean visible = aLabel.isVisible();
visible = !visible;
aLabel.setVisible(visible);
}
}
|
The Relational Operators
Although boolean literals and boolean variables can be useful, most of the time, instead of using boolean literals and boolean variables, you'll create boolean values by using the relational operators, often in conjunction with a selection or iterative conditional statement.
Java has the following six relational operators, which compare two values and then produce a boolean value.
| < |
less than |
| > |
greater than |
| <= |
less or equal |
| >= |
greater or equal |
| == |
equal |
| != |
not equal |
The first four of these operators are called the inequality operators, while the last two are called the equality operators. Those operators that require two symbols [<=, >=, ==, and !=] must be typed with no space between the two symbols. If you come from another programming language, here are some potential pitfalls you should look for:
- The equality operator is ==, not = , which is the assignment operator. The error message you'll encounter when you make this error is not very informative. Nevertheless, it's better than C++, where you may not even get an error message. The inequality operator is !=, not <>. Again, the error message is not very helpful.
- Make sure you use >= for greater-than or equal, and not =>, which is not a valid symbol.
Primitive Relations
As you can see from the figure, each of the relational operators requires two primitive operands, and the expression produces a boolean [true/false] result.
This only works with comparable primitive types, but most types are comparable. You normally don't have to worry about mixed-type comparisons; for the most part, they will work just like you'd expect.
Here are some examples:
|
Variables
|
Comparisons
|
byte b = 2;
short sh = 3300;
double d = 2.34;
float f = 2.34F;
char c = 'A'; |
b > sh is false
c < b is false
f == d is false
f < d is true
c >= d is true |
As you can see, you can compare characters, integers [both large and small] and floating-point numbers, with wild disregard for the type of each operand. There is, however, one place where you must be especially wary: when you compare two floating-point numbers.
Floating-point Relations
As a general rule, you should never compare two floating point operands using the equality operators [!=, == ]. For instance, the two floating-point values 2.34 and 2.34F are never equal, because they have different bit patterns.
Furthermore, calculations involving floating-point numbers are done in binary, so even if all operands have the same type, you cannot be sure that the bit-patterns will match exactly. Here's an example. Look at this expression. Is it true or false?
You may be surprised to find out that Java considers this true. (If you haven't had much exposure to binary floating-point numbers, of course, you probabally aren't surprised.) If the previous expression is true, then what about this:
| (.1+.1+.1+.1+.1+.1+.1+.1+.1+.1) == 1.0 |
Obviously, this is mathematically the same expression as the other, yet Java considers this one to be false. Beginning programmers often think that this is a bug, but it is not. This is not a bug in Java, or its ability to add. This is the way that binary floating-point numbers work.
Object Relations
In addition to comparing primitives, you can also use the equality operators to compare objects and Strings. Unlike primitive comparisons, where you can mix your types with abandon, you can only compare a String with another String, a Button with another Button, and so forth.
You also cannot compare object or String variables using the inequality operators. For instance, these are legal expressions:
"Hi" != "Mom"; // result is true
"dad" == "Dad"; // result is false |
These are illegal expressions:
Button b = new Button("Mom");
"Mom" < "Dad"; // no inequality operator
b == "Mom"; // compare String & Button |
Equality vs Identity
When you use the equality and inequality operators with Strings or objects, you are comparing the identity of the two objects, not their contents. Specificially, you are asking if both object references refer to the same object.
Here's an example using Buttons:
Button a = new Button("Hi Mom");
Button b = new Button("Hi Mom");
Button c = b; |
Here are the results of using the realtional operators with these Buttons:
a == b; // false - different buttons
b == c; // true - same button
a == c; // false - different buttons |
String Relations
With Strings, things can get a little more confusing than with objects like Buttons. In one sense, Strings work exactly like other objects; if you use the equality operator, you are asking whether those two String object are the same String object.
Strings can be more confusing than Buttons, however , because Java will automatically share the same actual String between several references. Here's an example that uses the same names as previously:
String a = "Hi Mom";
String b = "Hi Mom";
String c = b; |
You might expect, given the Button example, that a == b would be false, but that's not the case, because Java actually stores the characters "Hi Mom" only once. The String b does not create a second copy. Thus, all three String variables, a, b, and c, refer to exactly the same words.
Selection
The relational operators and the boolean values that they produce, are important because they allow us to implement selection. Selection acts like a “highway divider” in your code.
In selection, a relational operator is normally used to test two values. This test is called a condition. If the result of the test is true, then a particular section of code is executed; if the condition is false, then that section of code is skipped, and, perhaps, an alternative section of code is executed.
Here is an example:
If your salary is less than $ 25,000 then
Calculate tax based on 15% marginal rate
otherwise
Calculate tax based on 15% base rate
and a 28% marginal rate |
Selection is also called branching, because any time you run the program you may take a different path through the code. Java has five different kinds of branching or selection statements that you will learn about in this lesson:
- The if statement The if-else statement Nested if and if-else- if statements The switch statement
- The conditional operator [?:]
Something to Talk About
How does Java evaluate the following expressions? [That is, what are the results? Note that some expressions may contain syntax errors and will not compile.]
- 'A' == 65; 'Z' < 'a'; 'B' = 66; 3 <> 55; "Bob" <= "Alice"; 1.0F == 1.0;
- 10 != 10;
Please continue to the next section of this lesson.
|