Java Program to Check Leap Year

 

javaknowhow.blogspot.com

Java Program to Check Leap Year

What is a Leap Year?

Our earth orbits the sun in approximately 365.25 days which is called Solar year. We only take 365 days for One year and the remaining .254 multiplied with 4 and it comes out approximately 1 that is an extra day and this one day added to every four years in February that is 28 + 1 =29, this extra day February the year is called Leap year.

In the following java program, we have input a year and check the year leap year or not without any method.

import java.util.*;

public class LeapYearInJava

{

    public static void main(String[] args)

    {

        int year, flag;

        Scanner sc = new Scanner (System.in);

        System.out.println("Enter Year to Check Leap year or not:");

        year = sc.nextInt();

        flag = 0;

        if(year % 4 == 0)

        {

            if( year % 100 == 0)

            {

                if ( year % 400 == 0)

                {

                    flag = 1;

                }

                else

                {

                    flag = 0;

                }

            }

            else

            {

                flag = 1;

            }

        }

        else

        {

            flag = 0;

        }

        if(flag == 1)

        {

            System.out.println(year + " is a Leap Year.");

        }

        else

        {

            System.out.println(year + " is not a Leap Year.");

        }

    }

}

In the following java program of Leap year we have created one method boolean isLeapYear(int yr) to check leap year.

Java Program to Check Leap Year with Method

import java.util.*;

public class LeapYearInJavaWithMethod

{

    int year;

    boolean flag;

    // Constructor to initialize flag to true

    public LeapYearInJavaWithMethod()

    {

        flag = false;

    }

    // Leap year checking method

    boolean isLeapYear(int yr)

    {

        year = yr;

        if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))

        {

            flag = true;

        }

        else

        {

            flag = false;

        }

        return flag;

    }

    // main method

    public static void main(String[] args)

    {

        int year;

        boolean leap;

        LeapYearInJavaWithMethod ob = new LeapYearInJavaWithMethod();

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter Year to Check Leap year or not:");

        year = sc.nextInt();

        leap = ob.isLeapYear(year);

        if(leap == true)

        {

            System.out.println(year + " is a Leap Year.");

        }

        else

        {

            System.out.println(year + " is not a Leap Year.");

        }  

    }

}

Output

Enter Year to Check Leap year or not:

2021

2021 is not a Leap Year.

Enter Year to Check Leap year or not:

2004

2004 is a Leap Year.

 

Java program



SHARE THIS
Previous Post
Next Post