Incremental Java
if statement

Running Statements Conditionally

So far, we've only seen straight-line code, with some jumping around due to method calls.

However, we haven't given you a way of executing a statement only some of the times.

An if statement allows you to do this.

We introduce the if statement by giving you an example to give you the intuition, then talking about the syntax (i.e., the rules to write it down) and finally the semantics (i.e., explaining how it works).

Example

Let's define a simple method.
public void printIfEven( int num )
{
   System.out.println( "START" ) ;          // LINE 1
   if ( num % 2 == 0 )                      // LINE 2
      System.out.println( "num is even" ) ; // LINE 3
   System.out.println( "END" ) ;            // LINE 4
}
What happens if you have a method call: obj.printIfEven( 4 )? It prints:
START
num is even
END
Why does it print this? We examine the code above, and trace it. First, 4 is passed to num, the parameter variable, and used to initialize it.

Then, we run LINE 1 which prints "START". Then, we run LINE 2. This evaluates a condition num % 2 == 0, which checks if a number is even or not. If this condition evaluates to true, it runs LINE 3, otherwise it skips LINE 3 and runs LINE 4.

Since num is 4, and it's even, it runs LINE 3 and LINE 4, which prints "num is even" and "END", respectively.

num is odd

Suppose the method call is: obj.printIfEven( 3 ).

We still run LINE 1 as usual.

Then, the condition in LINE 2 evaluates to false, so we skip over LINE 3. The output is:

START
END

Syntax

The syntax describes the "grammatical" rule for an if statement. Here's how it looks:
if ( cond )  // if header
   if body   // if body
where cond is a condition (i.e., a Boolean expression).

The if body is a little more complicated. It can either be:

In the last lesson, we talked about blocks. So now let's discuss what a single statement is.

Single Statement

Right now, a single statement is: You've seen the first three. An empty statement is just a plain semicolon. It would look like:
if ( num % 2 == 0 )
   ; // Empty statement.  Does nothing.
A plain semicolon does nothing. It just skips it and goes on. It may seem silly, but there are a few occasions where you want to use it (though you can always work around this).

Let's look at an example of each kind of single statement used as an if body.

Declaration as if body

It's rare to do this since the declaration has limited scope.
if ( num % 2 == 0 )
   int x = 3 ;

Assignment Statement as if body

Assignment statements are common as bodies.
if ( num % 2 == 0 )
   total += 2 * num ;

Method Calls as if body

Method calls are also common.
if ( num % 2 == 0 )
   System.out.println( "It's even!" ) ;

Empty Statements as if body

Empty statements are uncommon.
if ( num % 2 == 0 )
   ;  // Empty statements are uncommon

if Statements as if body

This is called a nested if statement. This is when you have an if statement in an if body.
if ( num % 2 == 0 )
   if ( num > 10 )
      System.out.println( "Here we are!" ) ;
It may seem strange that an if statement is one statement. We'll see an even better example in the next section.

Block as if body

You can also have a block as the if body.
if ( first < second )
{
   int temp = first ;
   first = second ;
   second = temp ;
}
Notice that we have a block of 3 statements in the if body.

This if statement is considered a single statement. It has 3 statements in it, but it's considered a single statement.

The best analogy I can think of is this. You wish to send several boxes of candy to a friend. The post office charges an amount per box, plus an amount per weight. For example, they might charge $1 per box, and $1 per pound of weight.

However, you think to yourself "I shall buy myself a large box and place all the boxes of candy inside". Then, you are charged only $1. Since the post office doesn't care what's inside, they don't notice that there are several boxes inside the big box. They just see the one big box.

Similarly, we just see the one if statement, even if it's if body has several statements.

This allows us to write:

if ( num % 2 == 0 ) // Outer if
   if ( first < second ) // Inner if
   {
      int temp = first ;
      first = second ;
      second = temp ;
   }
The if body of the outer if statement is the inner if statement. Since the inner if statement is a single statement, it doesn't need braces.

Always Use Braces?

Some programmers believe that if bodies should always be in a block. They argue that it makes it easier to remember. Otherwise, you have one rule for single statements, and one for potentially multiple statements. It never hurts to add the braces, they say, and furthermore, should you decide to put two or more statements, the braces are already there.

So instead of:

if ( num % 2 == 0 ) 
   System.out.println( "It's even!" ) ;
you would write:
// Using a block for if-body, even though it has
// a single statement, and doesn't require a block
if ( num % 2 == 0 ) 
{
   System.out.println( "It's even!" ) ;
}
The meaning isn't any different. It just uses up a little more space.

If you're confused about single statements, then use this rule. The if body must be in a block. You shouldn't go wrong if you code this way.

Semantics

We've looked at a lot of if statements without saying what Java does when it runs it. Well, we did say what it did, but let's now say it more formally.
if ( cond )  // if header
   if body   // if body
The semantics are:
If cond evaluates to true, run the if body, else skip the if body.
I'm sure that's not too surprising.