Java Notes

if Statement - Overview

Purpose

The purpose of the if statement is to make decisions, and execute different parts of your program depending on a boolean true/false value. About 99% of the flow decisions are made with if. [The other 1% of the decisions use the switch statement.]

General Forms

The if statement has this form, where condition is true or false.

... // Do these statements before.
if (condition) {
    ... // Do this clause if the condition is true.
}
... // Do these statements after.

or

... // Do these statements before.
if (condition) {
    ... // Do this clause if the condition is true
} else {
    ... // Do this clause if the condition is false
}
... // Do these statements after.

Example - EvaluateScore.java

This displays one of two messages, depending on an input value.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
// Description: Evaluate a test score.  Illustrates if statement.
// File  : if/EvalScore.java
// Author: Fred Swartz - 2007-04-09 - Placed in public domain.

import javax.swing.*;

public class EvalScore {
    public static void main(String[] args) {//... Input a score.
        String scoreStr = JOptionPane.showInputDialog(null, "Enter your score?");
        int score = Integer.parseInt(scoreStr);
        
        //... Create a message.
        String comment;   // Message to the user.
        if (score >= 60) {
            comment = "Not so bad";
        } else {
            comment = "This is terrible";
        }
        
        //... Output the message.
        JOptionPane.showMessageDialog(null, comment);
    }
}

Flowchart representation of if statement

The flow of execution in a program is sometimes represented by a flowchart. Flowcharts are sometimes a good way to outline the flow in a method, especially if it gets complex. They may be useful in user documentation, but most flowcharting is done in quick sketches, which are thrown away once the program is written.

Decisions (if statements) are written in diamonds, and computational processes are written in boxes. There are several styles, and here is one of the most common.

Alternate ways to write the above if statement

There are lots of ways to write the above if statement. Here are some.

  1. Reverse the condition. Which to put first? There are two practices: Either put the normal case first, or the case that makes the boolean condition easiest to read.
            String comment;   // Message to the user.
            if (score < 60) {
                comment = "This is terrible";
            } else {
                comment = "Not so bad";
            }
  2. Initialize the variable to a default value, and only change it if necessary. This is often used when the condition is only rarely true.
            String comment = "Not so bad;   // Message to the user.
            if (score < 60) {
                comment = "This is terrible";
            }
  3. BAD: Two ifs. This is almost always a bad way to write an if-else. It's confusing to read, border values can slip through, and both conditions must be evaluated (inefficiency).
            // BAD BAD BAD BAD BAD BAD BAD BAD BAD
            String comment;   // Message to the user.
            if (score < 60) {
                comment = "This is terrible";
            }
            if (score >= 60) {
                comment = "Not so bad";
            }

Brace style

Always write braces. It is good programming style to always write the curly braces, {}, altho they are not needed if the clause contains only a single statement. There are two reasons this is good.

History. Braces have been used in most language that have descended from Algol, including C, C++, Java, C# etc because language designers want to make it easy for programmers in earlier languages to make the transition. Braces are an annoying and error prone, and numerous languages, eg, Visual Basic and Python, have tried to choose better notation.