Thursday, 22 October 2020

Java program to check year is a leap year or not

 

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.


  1. public class LeapYear {
  2.  
  3. /**
  4.   * Check year is a leap year or not
  5.   *
  6.   * @param args
  7.   */
  8. public static void main(String[] args) {
  9.  
  10. // using java if-else
  11. System.out.println("==== using java if-else ===");
  12. checkLeapYear(2000); // Output -> 2000 is a leap year
  13. checkLeapYear(2020); // Output -> 2020 is a leap year
  14. checkLeapYear(2002); // Output -> 2002 is a leap year
  15. checkLeapYear(2012); // Output -> 2012 is a leap year
  16. checkLeapYear(1998); // Output -> 1998 is a leap year
  17.  
  18. // using java ternary operator
  19. System.out.println("==== using java ternary operator ===");
  20. checkLeapYearUsingTernary(2000); // Output -> 2000 is a leap year
  21. checkLeapYearUsingTernary(2020); // Output -> 2020 is a leap year
  22. checkLeapYearUsingTernary(2002); // Output -> 2002 is a leap year
  23. checkLeapYearUsingTernary(2012); // Output -> 2012 is a leap year
  24. checkLeapYearUsingTernary(1998); // Output -> 1998 is a leap year
  25. }
  26.  
  27. // using java if-else
  28. private static void checkLeapYear(int year) {
  29. if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
  30. System.out.println(year + " is a leap year");
  31. } else {
  32. System.out.println(year + " is not a leap year");
  33. }
  34. }
  35.  
  36. // using java ternary operator
  37. private static void checkLeapYearUsingTernary(int year) {
  38. String result = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ?
  39. year + " is a leap year" : year + " is not a leap year";
  40. System.out.println(result);
  41. }
  42. }

Output -
====  using java if-else ===
2000 is a leap year
2020 is a leap year
2002 is not a leap year
2012 is a leap year
1998 is not a leap year
====  using java ternary operator ===
2000 is a leap year
2020 is a leap year
2002 is not a leap year
2012 is a leap year
1998 is not a leap year

No comments:

Post a Comment