Program to Check if a Year is a Leap Year in Java
Checking Leap Year
A leap year is a year that is evenly divisible by 4, except for years that are evenly divisible by 100. However, years divisible by 400 are also considered leap years.
We will explore different methods to check if a year is a leap year using Java programming.
Method 1: Using if-else Statement
We use an if-else statement to check if a year satisfies the leap year conditions.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a year: "); int year = scanner.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"); } scanner.close(); } }
Output:
Enter a year: 2024 2024 is a leap year
Method 2: Using Ternary Operator
We use the ternary operator to check leap year conditions in a single line.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a year: "); int year = scanner.nextInt(); String result = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) ? (year + " is a leap year") : (year + " is not a leap year"); System.out.println(result); scanner.close(); } }
Output:
Enter a year: 2023 2023 is not a leap year
Method 3: Using Function
We create a function to check if a year is a leap year and return the result.
import java.util.Scanner; public class Main { public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a year: "); int year = scanner.nextInt(); if (isLeapYear(year)) { System.out.println(year + " is a leap year"); } else { System.out.println(year + " is not a leap year"); } scanner.close(); } }
Output:
Enter a year: 2000 2000 is a leap year