Java program to check leap year
To check if a year is a leap year in Java, you can use the following logic:
- A year is a leap year if it is divisible by 4.
- If a year is divisible by 100, it is not a leap year, unless it is also divisible by 400.
Here's an example program that demonstrates how to check if a year is a leap year in Java:
public class LeapYear { public static void main(String[] args) { int year = 2020; boolean isLeap = false; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { isLeap = true; } } else { isLeap = true; } } if (isLeap) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } }
In this program, we define an integer variable year
and initialize it with the year we want to check. We also define a boolean variable isLeap
and initialize it to false
.
We then use a series of if
statements to check if the year is a leap year. If the year is divisible by 4, we check if it is also divisible by 100. If it is, we check if it is also divisible by 400. If it is, the year is a leap year. If not, it is not a leap year.
After checking if the year is a leap year, we print out a message to the console using the System.out.println
method.
When you run the program, the output will be:
2020 is a leap year.
As you can see, the program successfully checks if a year is a leap year and prints a message to the console.