Lesson 5.2 The if Statement
The if statement is the first, and simplest, branching instruction that we'll cover. Like classes and methods, the if statement consists of two parts: a header and a body.
With the if statement, the "header" is a boolean condition to be tested. The body of the if statement contains code to be executed. Each if executes a single section of code after testing its boolean condition. If the condition is true, then the code is executed; if the condition is false, the code is skipped.
Unlike a method body, the code contained in the body of an if statement does not need to be enclosed in braces. If you do not use braces, however, only a single statement will be executed.
Syntax
This illustration shows the syntax of the if statement [click image to enlarge]. The important points to understand are:
- The if statement begins with the keyword if. It must be in lowercase; you cannot use If or IF.
- The condition following the if keyword must--when evaluated--produce a boolean value. That means you can use constants [although you really shouldn't], boolean variables, or [most likely] a relational expression.
- Make sure you don't put a semicolon after the condition. This is known as a null statement. It is perfectly legal, but meaningless. If you put a semicolon after the condition, you are saying, "In the event that this condition is true, don't do anything."
- The parentheses are required.
- The body of an if statement is a single statement, ending with a semicolon. The statement will be executed if the condition is true.
An Example
Here's an example applet that shows how you'd use the if statement to determine which Button, of two, was pressed, using only a single actionPerformed() method.
// Example 5a - The if statement
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Example5a extends Applet
implements ActionListener
{
Button green = new Button("Green");
Button red = new Button("Red");
public void init()
{
add(red);
add(green);
red.addActionListener(this);
green.addActionListener(this);
}
public void
actionPerformed(ActionEvent e)
{
Object pressed = e.getSource();
if (pressed == red)
setBackground(Color.red);
if (pressed == green)
setBackground(Color.green);
}
}
|
Inside Example5a.java
The main structure of the applet should be familiar to you by now.
- It imports the necessary packages and implements the ActionListener interface.
- The class contains two attributes: the Button objects red and green.
- In the init() method, both buttons are added to the applet.
- Both buttons are then told to send their ActionEvents to the applet, using addActionListener().
Since both buttons send their messages to the same event handler, you'll have to sort out who clicked what in your actionPerformed() method. You'll do that by using an if statement.
Inside actionPerformed()
When the actionPerformed() method is called, Java sends along the ActionEvent object that triggered the event. This ActionEvent object contains a variety of useful information. You've already seen how you can, in a mouseMoved() method, extract the x, y coordinates of the mouse by sending the MouseEvent object the getX() and getY() messages. In the same way, you can also find out "who" generated this particular ActionEvent by sending it the getSource() message.
The getSource() method returns an Object, not a Button or TextField, but, since both Button objects and TextField objects are Object objects [since the Object class is their ultimate ancestor], we can compare the Object returned from the getSource() method with our two Button objects. Here's how:
- Send the ActionEvent argument the getSource() message. In this example, the argument is named e. Save the result in a local Object variable. Here, the variable is called pressed.
- Using the if statement, compare the pressed variable to the Buttonred. You remember from Lesson 5.1, "Relations", that the equality operator can be used to compare two objects, and that it compares whether two objects are, in fact, identical. If the result is true, then set the background of your applet to red.
- Now, do the same thing with the Button object named green. Add another if statement and this time compare pressed to green. If they match, then set the color of your applet to green.
Using if-else
One problem with Example5a.java is that when you press the red button, your code still checks the green button as well. This makes no sense at all because the two choices are obviously mutually exclusive:
- If red was clicked then green could not have been clicked.
- If green was pressed then red could not have been pressed.
- If neither button was pressed, then the actionPerformed() method would not have been called.
Since it is obviously inefficient to test a condition that we already know is false, Java provides a second portion for the if statement, called the else clause. You can see the syntax for the if-else statement in the illustration. [click to enlarge].

When you use the else keyword, the if statement takes one action when a test is true, and a different action when the test is false. This is much more efficient because the original comparison is made only once.
Multiple Statements
Often, you need to execute more that one statement whenever a logical condition is true. In such cases, you enclose the if-else statement body in braces, just like you would for the body of a class or method. The illustration [click to enlarge] shows the syntax of the multi-line if-else statement.
Indentation, Style, and Pitfalls
When you write an if statement, you should indent the statements inside the body of the if and the else portions. Each line should be indented at least two spaces and no more than five spaces.
If you are using a programmers editor, you can use the TAB key to insert the spaces, but you will often need to change the default setting from 8 spaces. If you are using Windows Notepad, you'll have to insert spaces, because Notepad inserts actual TAB characters into the text and doesn't give you a way to change th display.
Indenting Styles
There are three acceptable indentation styles you can use. Make sure that you choose one and stick to it.
The first style is the traditional 'C' style. It places the opening brace on the same line as the if statement contition. Each line inside the body is indented, and the closing brace is lined up with the if keyword. Here's an example of traditional indentation:
| Indentation Style 1 |
if (amountSold <= 35000) {
bonusPct = .035;
bonusAmt = amountSold * bonusPct;
}
else {
bonusPct = .075;
bonusAmt = amountSold * bonusPct + 100;
} |
The second style looks exactly like the traditional 'C' style, but it lines up the opening brace below the if, just as with the closing brace.
The advantage of this style [which I prefer] is that it makes it easy to match your braces without looking back and forth at the right and left margins. The disadvantage is that your listing is longer and you can see less of the code when looking at the screen.
The same code used above, when formatted in this syle looks like this:
| Indentation Style 2 |
if (amountSold <= 35000)
{
bonusPct = .035;
bonusAmt = amountSold * bonusPct;
}
else
{
bonusPct = .075;
bonusAmt = amountSold * bonusPct + 100;
} |
Finally, some programmers use a modification of the previous style, but line up the opening and closing braces with the indented code. In this style, your control struture would look like this:
| Indentation Style 3 |
if (amountSold <= 35000)
{
bonusPct = .035;
bonusAmt = amountSold * bonusPct;
}
else
{
bonusPct = .075;
bonusAmt = amountSold * bonusPct + 100;
} |
Why Use Braces?
Braces are not required when the body of an if statement consists of a single line of code. Nevertheless, it is a good idea to put them in. Here's why.
Suppose that you wrote the original code, listed above, so that a salesperson with sales above $35,000 received a 7-1/2 % bonus, and salespersons earning less than that received a 3-1/2 % bonus. Your original code might look like this:
| Original Program |
if (amountSold <= 35000)
bonusPct = .035;
else
bonusPct = .075;
bonusAmt = amountSold * bonusPct; |
After this original program, however, your company decides that the high-performing salespeople should each get an additional bonus of $100 as well, so you add the following lines of code:
| Modified Program |
bonusAmt = 0;
if (amountSold <= 35000)
bonusPct = .035;
else
bonusPct = .075;
bonusAmt += 100;
bonusAmt += amtSold * bonusPct; |
Despite your best intentions and the fact that the program compiles, it does not do what you want it to do.
Because the body of the else portion of the if statement does not use braces, it consists of the single statement assigning a bonusPct of 7-1/2 %. The following statement, which you intended to apply only to high-performing salespeople, is, despite the indentation, applied to everyone.
My personal rule of thumb to avoid this kind of problem is to always use braces for an if statement, unless the entire statement can fit on one line, like this:
| if (amt < 100) cost = .23; |
The Phantom Semicolon
A second common mistake when writing an if statement is to insert a semicolon after the if statement condition, like this:
if (employeesInBuilding == 0);
{
demolishBuilding();
} |
Despite the admirable safety-check applied in this example, the building is still demolished, no matter how many people are inside. This null statement says, in effect.
- Check to see if employeesInBuilding is zero.
- If employeesInBuilding is zero, then do nothing [the null statement]
- After checking how many employees are in the building, call the demolishBuilding() method.
Note that demolishBuilding() does not depend upon the state of employeesInBuilding.
The Conditional Operator
One problem with using if-else is that you can't use an if-else in a formula or expression. if-else is a statement; it does not produce a value. That means, you must create an additional variable, like bonusPcnt in the previous example.
Java's, conditional operator provides a way to use an if-else condition inside an expression. [Click the illustration to expand]. The conditional operator is sometime called the ternary operator, because it is the only operator to require three operands.

The operands of the conditional operator are:
- The condition or test expression: This must be some expression that evaluates to a boolean value.
- The true result: If the condition portion is true, then the wholeexpression takes on the value listed in this clause. This value can be of any type.
- The false result: If the condition portion is false, then the whole expression takes on the value listed here. This value can also be of any type, but should match the type of the true result.
- The condition is separated from the results portion by a colon [:]. The results are separated by a question mark [?].
We could calculate bonusAmt, used in the previous examples, like this:
bonusAmt = amountSold <= 35000 ?
amountSold * .035 :
100 + amountSold * .075; |
This example has been formatted so that each operand used by the conditional operator appears on a separate line, but that's not required.
You can also nest another conditional expression [using the conditional operator] inside the true or false portions of a first conditional expression. This quickly becomes unreadable, however, and, despite what you might think, may even execute more slowly. You should attempt to write source code that is clear and to-the-point, not code that uses the fewest possible lines.
Something to Talk About
Wanna try something fun? Download, compile, and run Example5a listed above. When you are finished, modify the program so that it:
- Adds a Label object, in addition to the two Button objects. Have the Label say whatever you like.
- Uses if-else, instead of if.
- Performs two actions inside both the if and the else portions. If the red button is clicked, then turn the applet background red, and make your Label background green. If the green button is clicked, then make the applet background green and make the Label background red.
Your program will look something like this:
Please continue to the next section of this lesson.
|