Java Check Leap Year Example

This example will tell you how to check whether a year is a leap year or not. As we know, leap year is an integer that can be divided by 4 but can not be divided by 100. For example, 1996 is just a leap year while 1900 is not. But if a year can be divided by 400, it is also a leap year.

1. Java Check Leap Year Example.

  1. CheckLeapYear.java
    package com.dev2qa.java.basic;
    
    import java.util.Scanner;
    
    public class CheckLeapYear {
    
        public static void main(String[] args) {
    
            // Wrap command line console input to a Scanner object.
            Scanner scanner = new Scanner(System.in);
    
            System.out.println("Please input a year.");
    
            while(true)
            {
                // Get user input year string value.
                String year = scanner.nextLine();
    
                if("quit".equalsIgnoreCase(year))
                {
                    System.out.println("Program exit.");
                    break;
                }else
                {
                    long yearLong = getLong(year);
    
                    if(yearLong > -1)
                    {
                        if(((yearLong % 4 == 0) && (yearLong % 100 != 0)) || yearLong % 400 == 0)
                        {
                            System.out.println(year + " is a leap year. ");
                        }else
                        {
                            System.out.println(year + " is not a leap year. ");
                        }
                    }
                }
            }
        }
    
        /* Get long value of input string. */
        private static long getLong(String value)
        {
            long ret = -1;
    
            try {
                ret = Long.parseLong(value);
            }catch(NumberFormatException ex)
            {
                System.err.println("The input text is not a number.");
            }finally
            {
                return ret;
            }
        }
    
    }
  2. When running the above code, it will prompt you to input a year value. If the value is not a number then it will print out an error message. Otherwise, it will print out related messages to show whether the year is a leap year or not.
    Please input a year.
    
    qqqq
    The input text is not a number.
    
    1996
    1996 is a leap year.
    
    1900
    1900 is not a leap year.
    
    2000
    2000 is a leap year.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x