java
Parameters: int year
Year: The year to be checked
Returns: Boolean: true if year is leap year, false otherwise
The CheckLeapYear function receives a year as input and checks whether it's a leap year. It implements conditional logic and uses the concept of modules to return a boolean value.
Hello there, programmer! This simple, yet informative blog post will guide you through the essentials of programming a function in Java to accurately determine if a given year is a leap year or not. No need for complexity or jargon; we're keeping it as straightforward as possible. Dive right into the steps below and see how it gets done.
The first step in writing the function for checking a leap year in Java is to understand the problem. A leap year is a year that is exactly divisible by 4 except for end of century years which must be divisible by 400. This means that the year 2000 was a leap year although 1900 was not.
To implement this, you need a function that accepts a year as an input and then checks the following conditions:
public boolean checkLeapYear(int year) {
// Initial step: Check if year is divisible by 4
if(year % 4 == 0) {
// Further steps will be added in the next steps
}
}
The next step is to handle the condition of non-century years. According to the leap year rules, all non-century years which are divisible by 4 are leap years.
public boolean checkLeapYear(int year) {
if(year % 4 == 0) {
if(year % 100 != 0) {
// If year is not a century year, it is a leap year
return true;
}
}
}
The next step is to add handling for century years. Century years that are exactly divisible by 400 are leap years.
public boolean checkLeapYear(int year) {
if(year % 4 == 0) {
if(year % 100 != 0) {
return true;
} else if(year % 400 == 0) {
// If year is a century year and is divisible by 400, it is a leap year
return true;
}
}
}
If none of the above conditions are met, that means the year is not a leap year. So, return false.
public boolean checkLeapYear(int year) {
if(year % 4 == 0) {
if(year % 100 != 0) {
return true;
} else if(year % 400 == 0) {
return true;
}
}
return false;
}
The final step is to test your function with different inputs to ensure it is working correctly.
public static void main(String[] args) {
System.out.println(checkLeapYear(2000)); // Output: true
System.out.println(checkLeapYear(1900)); // Output: false
System.out.println(checkLeapYear(2020)); // Output: true
System.out.println(checkLeapYear(2021)); // Output: false
}
In the conclusion, this function successfully checks if a given year is a leap year or not using Java.
The CheckLeapYear function utilizes the GregorianCalendar system's principle. According to this, a leap year is divisible by 4, but not 100 unless it is also divisible by 400. Therefore, `if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))` will return 'true' for a leap year.
Learn more