Java program to check year is a leap year or not using if-else and java ternary operator
We are going to create a java program to check that the input year is a leap year or not. First, we will use the java if-else condition to check leap year, and then we also use the java ternary operator to check leap year.
A year is a leap year if the input year is divisible by 400 or the input year is divisible by 4 but not divisible by 100.
Leap year examples -
1. Input year 2000 -> Divisible by 400, so it is a leap year.
2. Input year 2020 -> Divisible by 4 but not divisible by 100, so it is a leap year.
3. Input year 2002 -> Not divisible by 4 and not divisible 400, so it is not a leap year.
4. Input year 2012 -> Divisible by 4 but not divisible by 100, so it is a leap year.
5. Input year 1998 -> Not divisible by 4 and not divisible 400, so it is not a leap year.
- public class LeapYear {
- /**
- * Check year is a leap year or not
- *
- * @param args
- */
- public static void main(String[] args) {
- // using java if-else
- System.out.println("==== using java if-else ===");
- checkLeapYear(2000); // Output -> 2000 is a leap year
- checkLeapYear(2020); // Output -> 2020 is a leap year
- checkLeapYear(2002); // Output -> 2002 is a leap year
- checkLeapYear(2012); // Output -> 2012 is a leap year
- checkLeapYear(1998); // Output -> 1998 is a leap year
- // using java ternary operator
- System.out.println("==== using java ternary operator ===");
- checkLeapYearUsingTernary(2000); // Output -> 2000 is a leap year
- checkLeapYearUsingTernary(2020); // Output -> 2020 is a leap year
- checkLeapYearUsingTernary(2002); // Output -> 2002 is a leap year
- checkLeapYearUsingTernary(2012); // Output -> 2012 is a leap year
- checkLeapYearUsingTernary(1998); // Output -> 1998 is a leap year
- }
- // using java if-else
- private static void checkLeapYear(int year) {
- 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");
- }
- }
- // using java ternary operator
- private static void checkLeapYearUsingTernary(int year) {
- 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);
- }
- }
No comments:
Post a Comment