English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Online Tools

Each Loop

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Exception Handling

resources

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections/Java Input/Output (I

O Streams/Java Reader

Writer

New features

Java Examples Comprehensive

Java program to check if it is a leap year

In this program, you will learn how to check if a given year is a leap year. It uses if-else statements to check.4Leap years can be divided by4Divisible by 100 but not by 400 are not leap years.

Example: Java program to check for leap year

public class LeapYear {
    public static void main(String[] args) {
        int year = 1900;
        boolean leap = false;
        if(year %% 4 == 0)
        {
            if(year %% 100 == 0)
            {
                //a year can be divided by4000 is divisible by 100, therefore it is a leap year
                if ( year % 400 == 0)
                    leap = true;
                else
                    leap = false;
            }
            else
                leap = true;
        }
        else
            leap = false;
        if(leap)
            System.out.println(year + "is a leap year.");
        else
            System.out.println(year + "is not a leap year.");
    }
}

The output when running the program is:

1900 is not a leap year.

Change the value of year to2012The output is:

2012 is a leap year.

In the above program, the given year19000 is stored in the variable year.

because19000 is divisible by 100.4is divisible by 100, and it is also a century year (ending with 00), while a leap year can be divided by4000 is divisible by 100. Because19000 cannot be4000 is divisible by 100, so19000 is not a leap year.

However, if we change year to2000, then it can be4is divisible by 100, and it is also a century year, which can be divided by4000 is divisible by 100. Therefore2000 is a leap year.

Similarly, if we change the year to2012then the year can be divided by4and is not a century year, so2012is a leap year. We do not need to check2012a year can be divided by400 is divisible by 100.

Java Examples Comprehensive