3.3 Nested if Statement

In addition to chaining, you can also nest one conditional within another. We could have written the previous example as:

if (x == 0)
{
   System.out.println("x is zero");
}
else
{
   if (x > 0)
   {
      System.out.println("x is positive");
   }
   else
   {
      System.out.println("x is negative");
   }
}
    

Following program determines whether the year is a leap year or not.

Leap Years are any year that can be evenly divided by 4.  A year that is evenly divisible by 100 is a leap year only if it is also evenly divisible by 400.

import java.util.Scanner;  //Needed for Scanner object

/**
 *  This program demonstrates a nested if statement.
 */
public class Leapyear
{
   public static void main(String[] args)
   {
      int year;    // holds a year

      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);

      // Get the year.
      System.out.print("Enter a year : ");
      year = console.nextInt();

      // Determine whether the year is leap year.
      if (year % 4 == 0)
      {
         if (year % 100 == 0)
         {
            if (year % 400 == 0)
            {
               System.out.println("A leap year");
            }
            else
            {
               System.out.println("Not a leap year");
            }
         }
         else
         {
            System.out.println("A leap year");
         }
      }
      else
      {
         System.out.println("Not a leap year");
      }
   }
}

Output 1

Enter a year : 1992
A leap year

Output 2

Enter a year : 2000
A leap year

Output 3

Enter a year : 1900
Not a leap year

Output 4

Enter a year : 2015
Not a leap year