java

How to Check If a Year is a Leap Year in Java

In this tutorial, we are going to see how to check if a year is a leap year in Java. Before we see the program, let’s take a look at what a leap year is:

  • A normal year has 365 days.
  • A leap year has 366 days (the extra day is February 29).

 

How to Check If a Year is a Leap Year in Java
  • If a year is divisible by 4 means there is no remainder. If it’s not divisible by 4. It’s not a leap year. For example: 1997 is not a leap year.
  • If a year is divisible by 4, but not by 100. For example: 2012 is a leap year. If a year is divisible by 4 and 100, go to the next step.
  • If a year is divisible by 100, but not by 400. For example: 1900, then it is not a leap year. If a year is divisible by the two, then it is a leap year. 2000 is therefore a leap year.

 

 

Java Program to Check If a Year is a Leap Year :
import java.util.Scanner;

public class Main 
{
    public static void main(String args[])
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a year: ");
        int y = s.nextInt();
        boolean b = false;
        if(y % 400 == 0)
        {
            b = true;
        }
        else if (y % 100 == 0)
        {
            b = false;
        }
        else if(y % 4 == 0)
        {
            b = true;
        }
        else
        {
            b = false;
        }
        if(b == true)
        {
            System.out.println("The year "+ y +" is a leap year");
        }
        else
        {
            System.out.println("The year "+ y +" is not a leap year");
        }
    }
}

Output:

Enter a year: 2020
The year 2020 is a leap year
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *