Thursday, September 14, 2023

How to check leap year in Java - program example

Write a Java program to find if a year is a leap year or not is a standard Java programming exercise during various Java programming courses on schools, colleges, and various training institutes both online and offline,  along with other popular homework's e.g. printing Fibonacci numbers, checking palindromes, or finding prime numbers. Just to recap a leap year is a year with 366 days which is 1 extra day than a normal year. This extra day comes in the month of February and on leap year Feb month has 29 days than normal 28 days. If you are following then you might know that leap year comes in an interval of 4 years. This year 2012 is a leap year and Feb has 29 days, you can check.


Now if you are in programming before you might be familiar that there is standard logic to find leap year i.e. if a year is multiple of 400 or multiple of 4 but not multiple of 100 then it's a leap year. In addition to this standard logic, you can also use Java's Date, Time, and Calendar API to check how many days any year has and by comparing that number with 365 you can find whether that year is a leap year or not. 

In this Java programming tutorial, we will both of these examples to check if a year is a leap year or not.

And, if you are new to Coding and Programming then I also suggest you check out these free Programming courses to learn programming basics like operators, functions, classes, loops, etc in Java, Python, JavaScript, and other popular programming languages.


Java program to check if a year is a leap year

Here is a complete code example of a Java program to find out whether a year is a leap year or not. isLeapYear(int year) method uses Calendar API to get the maximum number of days in that year and compare that with 365. If the year contains more than 365 days, it's a leap year. The second method doesLeapYear(int year) uses programming logic to find if a year is a leap or not.

How to check leap year in Java - program example




How to check if a year is a leap year in Java

Here is our complete Java program to test if a given year is a leap year or not. 

package test;

import java.util.Calendar;

/**
 *
 * Java program to find if a year is a leap year or not.
 * A leap year is a year that contains 366 days, which is 1 day more than the normal 365 day year.
 * Leap year comes in an interval of 4 years. In Gregorian
 * calendar in leap year February has 29 days which is 1 day more than 28 day in a normal year.
 *
 * @author
 */

public class LeapYearProgram {
 
 
    public static void main(String args[]) {
 
        //Testing some leap and non-leap year using Java library code
        System.err.println("Is 2000 a leap year ? : " + isLeapYear(2000));
        System.err.println("Is 2012 a leap year ? : " + isLeapYear(2012));
        System.err.println("Is 1901 a leap year ? : " + isLeapYear(1901));
        System.err.println("Is 1900 a leap year ? : " + isLeapYear(1900));
     
     
        //Checking leap year without using library or API and applying logic
        System.err.println("Does 2000 a leap year : " + doesLeapYear(2000));
        System.err.println("Does 2012 a leap year : " + doesLeapYear(2012));
        System.err.println("Does 1901 a leap year : " + doesLeapYear(1901));
        System.err.println("Does 1900 a leap year : " + doesLeapYear(1900));
    }  
 
 
   /*
     * This method checks whether a year is a leap or not by using Java Date
     * and Time API. Calendar class has a utility method to return maximum
     * number of days in a year which can be used to check if its
     * greater than 365 or not
     */

   public static boolean isLeapYear(int year){
       Calendar cal = Calendar.getInstance(); //gets Calendar based on local timezone and locale
       cal.set(Calendar.YEAR, year); //setting the calendar year
       int noOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
     
       if(noOfDays > 365){
           return true;
       }
     
       return false;
   }
 
   /*
    * This method uses standard logic to check leap year in Java.
    * A year is a leap year if its multiple of 400 or multiple of 4 but not 100
    */

   public static boolean doesLeapYear(int year){
       return (year%400 == 0) || ((year%100) != 0 && (year%4 == 0));
   }
}

Output:
Is 2000 a leap year ? : true
Is 2012 a leap year ? : true
Is 1901 a leap year ? : false
Is 1900 a leap year ? : false
Does 2000 a leap year : true
Does 2012 a leap year : true
Does 1901 a leap year : false
Does 1900 a leap year : false


That's all on How to check if a year is a leap year or not in Java. I prefer to use library code instead of reinventing the wheel but if it's a homework or programming exercise, you are likely to be asked to do this using pure logic. By the way, this logic can be implemented in any other programming language like C, C++, or python as well.


Related Data Structure and Algorithm Interview Questions from Javarevisited Blog
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • Top 30 Array Coding Interview Questions with Answers (see here)
  • How to reverse an array in place in Java? (solution)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • Top 15 Data Structure and Algorithm Interview Questions (see here)
  • How to find a missing number in an array? (answer)
  • How to compare two arrays in Java? (answer)
  • Top 20 String coding interview questions (see here)
  • 50+ Data Structure and Algorithms Problems from Interviews (questions)
  • How to remove duplicate elements from an array in Java? (solution)
  • How to find all pairs whose sum is equal to a given number in Java (solution)
  • 5 Free Data Structure and Algorithms Courses for Programmers (courses)
  • Top 30 linked list coding interview questions (see here)
  • Top 50 Java Programs from Coding Interviews (see here)
  • 100+ Data Structure Coding Problems from Interviews (questions)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.

P. S. - If you are looking for some free data structure and algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data structure and algorithms courses. It's completely free and all you need to do is create a free Udemy account to enroll in this course. 

Lastly, what is your favorite Java programming exercise? Palindrom, Prime Number, Fibonacci series, Binary Search, or this one?  Do let me know in comments. 

10 comments:

  1. Instead of doing this , can we use modulo operator ?
    if(year%4==0)
    SOP("Leap year");
    else
    SOP("Not a leap year");

    ReplyDelete
    Replies
    1. Nope u can't,
      Check the conditions in the given code again !!

      Delete
  2. import java.util.*;
    class leap{
    p s v m(s args[])
    {
    S.o.p("enter year");
    int year=new Scanner(System.in).nextInt();
    S.o.p("given year is leapyear true or false:"+leapyear(year));
    }

    public static boolean leapyear(int year)
    {

    if(year%400==0)
    boolean = true;

    elseif(year%4==0 && year%100!=0)
    boolean = true;

    else
    boolean = false;

    }
    }

    ReplyDelete
  3. how about making the code a little shorter?

    public static boolean leapyear(int year){
    return ( year%400==0 || (year%4==0 && year%100!=0) )
    }

    ReplyDelete
  4. hello..!!

    by java.util.Calender class we got 500,600,700&900 etc years are as leaf year..!! but those are not leaf years ..!!

    ReplyDelete
  5. Scanner sc = new Scanner(System.in);
    System.out.print("Enter Year : ");
    int year=sc.nextInt();
    if((year%4==0&&year%100!=0)||(year%400==0)) {
    System.out.println(year+" is leaf year ");
    }else {
    System.out.println(year+" is not leaf year ");

    ReplyDelete
  6. The javadoc for GregorianCalendar says: "Before the Gregorian cutover [October 15, 1582], GregorianCalendar implements the Julian calendar. The only difference between the Gregorian and the Julian calendar is the leap year rule. The Julian calendar specifies leap years every four years, whereas the Gregorian calendar omits century years which are not divisible by 400."
    The described results are therefore correct.

    Please see https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4252550

    ReplyDelete
  7. The javadoc for GregorianCalendar says: "Before the Gregorian cutover [October 15, 1582], GregorianCalendar implements the Julian calendar. The only difference between the Gregorian and the Julian calendar is the leap year rule. The Julian calendar specifies leap years every four years, whereas the Gregorian calendar omits century years which are not divisible by 400."
    The described results are therefore correct.

    Please see as well: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4252550

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.