The following Program to Check if the Entered year is a leap year or not, the if-else statement has been used. If you want to learn about the if-else statement in Java, click the link below.
A leap year comes after every 4 years and has 366 days that year instead of 365 days. In the leap year, an additional day is added to the February month has 29 days instead of 28 days.
Now let us understand through mathematical logic,
- If a year is divisible by 4 then it is leap year.
- If a year is divisible by 400 and not divisible by 100 then it is also a leap year.
- Example: 2000, 2004, 2008, etc are the leap years.
Java Program to Check for Leap Year
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | //check for leap year in java import java.util.*; public class LeapYearJava { public static void main(String[] args) { int n; int year; Scanner sc = new Scanner(System.in); System.out.println("Enter the year"); n = sc.nextInt(); year = n; boolean leap = false; if (year % 4 == 0) { if (year % 100 == 0) { // year is divisible by 400, hence the year is a leap year if (year % 400 == 0) leap = true; else leap = false; } else leap = true; } else leap = false; //Display if (leap) System.out.println(year + " is a leap year."); else System.out.println(year + " is not a leap year."); } } |
Output:
Enter the year
2016
2016 is a leap year.