Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other words, A year that is completely divisible by 4 is called leap year. In each leap year, the month of February has 29 days instead of 28. For example, 1998, 1992, 1996, 2020. In this section, we will create a Java program to check the given year is leap year or not.
Let’s implement the above algorithm in a Java program.
Filename: LeapYearExample.java
Output:
In the above program, we can also implement the logic in a single statement like the following:
Explanation: While writing the code, the concept of short-circuiting is used. That is why we have three return statements in the code. Short-circuiting means if, at any point, we can make a decision, we should not be moving further to check other expressions. In our case, if any year is divisible by 400, we can say the year is a leap year. Hence, no need to check its divisibility with 4 or 100, and we can stop right here. If 400 does not divide the year perfectly, we move further and check its divisibility with 4 and 100. If the year is divisible by 4 and not by 100, we have got the leap year; otherwise, the year is not a leap year.
Designed by Elegant Themes | Powered by WordPress