AP Computer Science Java: Lesson 2.3
Conditional Statements - The If..Else Statement


Lesson 2.3 - The If..Else Statement

Purpose: To learn how write and use a Java if..else statement

A Fork in the Road
When the condition in an if statement is true, the computer performs the statements enclosed in the braces, then moves on to the next portion of the program. But what if the condition is false? The statements inside the braces are ignored and then the computer moves on to the next portion of the program. For example, in the code below, if x is not less than 10, nothing happens.

   if(x < 10)
   {
      System.out.println("Single-digit number");
   }

While this may be fine in some situations, many times we want the computer to perform one set of actions if a condition is true and another set of actions if the condition is false. This is a job for the if..else statement! Here's the format:

   if(condition)
   {
      list of statements...
   }

   else
   {
      other list of statements...
   }


The "list of statements" will be performed if the condition is TRUE while the "other list of statements" will be performed if the condition is FALSE. So unlike the if statement, in an if..else statement, something will occur.

Let's look at an example:

   if(x < 10)
   {
      System.out.println("Single-digit number");
   }

   else
   {
      System.out.println("Multi-digit number");
   }

The following is equivalent:

   if(x >= 10)
   {
      System.out.println("Multi-digit number");
   }

   else
   {
      System.out.println("Single-digit number");
   }

Note that in the second form, the condition is the opposite of the original. By switching the statements in the if and else portions, the result is the same.

Also, since there is only one statement in each block, the original if..else above could be written more compactly as

   if(x < 10) System.out.println("Single-digit number");
   else System.out.println("Multi-digit number");


In closing
, use an if..else when an action is necessary for both true and false values of the particular condition in your program.

© DanShuster.com