Program to Check Leap Year in Java

thumbnail

In this tutorial, we will learn about program to check if the given year is a leap year or not. The code will use if else statement.

First we have to know about leap year. A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400.

For example, given year 1900 is stored in the variable year. If we computer the varible year, 1900 is divisible  by 4 and also a century year because ending with 00. It has be divisible by 400 for a leap year. Since, 1900 is not divisible by 400, 1900 is not a leap year.

Likewise, if we change the value year into 2019. The result will be not a leap year.

But, if we change the value year into 2000 or 2012. The output will be a leap year.

Example: Check Leap Year in Java

import java.util.Calendar;
public class CheckLeapYear {
    public static void main(String[] args) {
        checkLeapYear();
    }
    public static void checkLeapYear(){
        int year = 2019;
        boolean isLeap = false;
        if(year % 4 == 0){
            if( year % 100 == 0){
                if ( year % 400 == 0){
                    isLeap = true;
                } else {
                    isLeap = false;
                }
            } else {
                isLeap = true;
            }
        } else{
            isLeap = false;
        }
        if(!isLeap){
            System.out.println(year + " is not a leap year.");
        } else {
            System.out.println(year + " is a leap year.");
        }
    }
}

The output will be:

1900 is not a leap year.
2000 is a leap year.
2019 is not a leap year.

To learn more about java you find it here.

Back To Top