The else statement | Decision making, Branching and Looping

The else statement

1) Defines an alternative and mutually exclusive logic path to be followed if the preceding if statement expression evaluates to false

2) Must always be paired with, and follow, an if statement. It can never be coded separately

3) Have two forms.

The general syntax is either of the following:
else statement;
or

else
{
statements;
}

The first form is often referred to as a “single statement else”.

For example,
if (amountDue > 0)
System.out.println(“You owe ” + amountDue);
else
System.out.println(“You owe nothing”);

will add to the grand total and display how much is owed if amountDue is greater than zero. Otherwise, the customerRating will be set to ‘A’ and the “You owe nothing” message will be displayed.

The two logic paths are mutually exclusive and merge at the first statement after the end of the else block.

4) Can trap programmers who get sloppy.

For example,
if (age < 65)
System.out.println(“Regular admission”);
else;
System.out.println(“Senior admission”);

will always display the “Senior admission” message no matter what value age has. The accidental semicolon after the else says that if the expression is false you want to do nothing. Logic then merges at the next statement, so the message is always displayed.

Nesting

 

It is permitted.
An if or an if-else can be coded within an if or an if-else.

Example:

import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

System.out.print(“Enter age: “);
Scanner Keyboard= new Scanner(System.in);
int age;
age=Keyboard.nextInt();
if (age >= 10)
{
if (age < 65)
{
System.out.println(“$5 admission”);
}
else
{
System.out.println(“$4 admission”);
}
}
else
{
if (age < 5)
{
System.out.println(“Free admission”);
}
else
{
System.out.println(“$2 admission”);
}
}

}
}
Output

Notes:

1. The program prompts for and reads a person’s age from the user.

2. Based upon the value of age, it displays a different admission fee (under 5 is free, 5-17 is 2 dollars, 18-64 is 5 dollars, and 65 and over is 4 dollars).