Find If a Number is a Leap Year in Java



In this article, we will learn to find if a year is a leap year or not using Java. Finding whether a year is a leap or not is a bit tricky. We generally assume that if a year number is evenly divisible by 4 is a leap year. But it is not the only case. A year is a leap year if ?

  • It is evenly divisible by 100
  • If it is divisible by 100, then it should also be divisible by 400
  • Except this, all other years evenly divisible by 4 are leap years.

Problem Statement

Write a program in Java to check if the given year is a leap year or not.

Input

Enter an Year :: 2002

Output

Specified year is not a leap year

Step to find if the given year is a leap year

Following are the steps to find if the given year is a leap year

  • First we will import the Scanner class from java.util package.
  • We will initialize the public class LeapYear.
  • Take integer variable year and will assign a value to the variable.
  • Check if the year is divisible by 4 but not 100, DISPLAY "leap year"
  • Check if the year is divisible by 400, DISPLAY "leap year"
  • Otherwise, DISPLAY "not leap year"

Java program to find if the given year is a leap year

Below is the Java program to find if the given year is a leap year ?

import java.util.Scanner;
public class LeapYear {
   public static void main(String[] args){
      int year;
      System.out.println("Enter an Year :: ");
      Scanner sc = new Scanner(System.in);
      year = sc.nextInt();

      if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
         System.out.println("Specified year is a leap year");
      else
         System.out.println("Specified year is not a leap year");
   }
}

Output 

Enter an Year ::
2020
Specified year is a leap year

Code Explanation

The program imports the Scanner class to take user input and checks if a year is a leap year. It first prompts the user to enter a year and stores it in the year variable. The program then checks two conditions: if the year is divisible by 4 but not by 100, or if it's divisible by 400. If either condition is true, it prints that the year is a leap year otherwise it prints that it's not.

Updated on: 2024-09-13T10:20:55+05:30

77K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements