Java Code for Leap Year. In this article, we are going to write a Java program that detects if a year is a leap year.
A leap occurring every four years, adds an extra day to the calendar year to synchronize it with the astronomical year. This additional day, February 29 compensates for the earth’s orbit around the sun taking approximately 365.25 days.
Table of Contents
Leap Year Condition
Before writing Java Code for Leap Year, it is crucial to understand the criteria that define a leap year-
- A year is a leap year if it is divisible by 4.
- However, if the year can be evenly divided by 100, it is not a leap year.
- Yet, if the year is also evenly divided by 400, then it indeed is a leap year.
Java Program for Leap Year
Now let’s write a Java program to check if a year is a leap year by using the leap year condition described above.
import java.util.Scanner;
public class leapjava {
public static void main(String[] args) {
int year;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the year to check if it is a leap year");
year = sc.nextInt();
if((year%4==0 && year%100!=0) || (year%400==0)){
System.out.println(year + " is a leap year");
}
else {
System.out.println(year + " is not a leap year");
}
}
}
Output
The above Java program checks if the year entered by the user meets the leap year criteria by using the if statement.
Happy Coding & Learning
3 thoughts on “Java Code for Leap Year”