In this tutorial, we will write a java program to check leap year using ternary operator. This program prompts user to enter a year. It then checks if it’s a leap year or not using the ternary operator. Let’s break down the condition used in the following program:
- Entered year is divisible by 4
- Not divisible by 100 unless it’s also divisible by 400.
If both the above statements return true then the condition as whole return true and "Leap year"
is assigned to result
String else "Not a leap year"
is assigned.
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
// Using ternary operator to check if the year is a leap year
String result = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? "Leap year" : "Not a leap year";
System.out.println(year + " is " + result);
scanner.close();
}
}
Output:
Enter a year: 2024
2024 is Leap year
In this example, the user entered 2024, the program output it as a leap year because it’s divisible by 4 and not divisible by 100 unless it’s also divisible by 400.
Leave a Reply