Java Program to Check Leap Year or Not

This article covers multiple programs in Java that checks whether an year entered by user at run-time of the program, is a leap year or not.

A leap year is an year that

To understand the logic behind above conditions, refer to Leap Year Logic. Now let's move on, and create the program.

Leap Year Program in Java

The question is, write a Java program that checks whether an year is a leap year or not. The year must be received by user at run-time. The program given below is its answer:

import java.util.Scanner;

public class fresherearth
{
   public static void main(String[] args)
   {
      int year;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the Year: ");
      year = scan.nextInt();
      
      if(year%4==0 && year%100!=0)
         System.out.println("\nIt is a Leap Year.");
      else if(year%400==0)
         System.out.println("\nIt is a Leap Year.");
      else
         System.out.println("\nIt is not a Leap Year.");
   }
}

The snapshot given below shows the sample run of above program with user input 1900 as year to check whether it is a leap year or not:

java check leap year

Here is another sample run with user input 2024 as year:

leap year progra in java

Check Leap Year using Conditional Operator in Java

This program does the same job as of previous program. This program uses conditional or ternary (?:) operator to do the job.

import java.util.Scanner;

public class fresherearth
{
   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the Year: ");
      int year = scan.nextInt();
      
      int check = ((year%4==0 && year%100!=0) || (year%400==0)) ? 4 : 0;
      if(check==4)
         System.out.println("\n" +year+ " is a Leap Year.");
      else
         System.out.println("\n" +year+ " is not a Leap Year.");
   }
}

Here is its sample run with user input 2000:

java check leap year using conditional operator

The above program can also be created in this way:

import java.util.Scanner;

public class fresherearth
{
   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the Year: ");
      int year = scan.nextInt();
      
      String check = ((year%4==0 && year%100!=0) || (year%400==0)) ? "yes" : "no";
      
      if(check.equals("yes"))
         System.out.println("\n" +year+ " is a Leap Year.");
      else
         System.out.println("\n" +year+ " is not a Leap Year.");
   }
}

You'll get the same output as of previous program.

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »