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 which can be divided by 4 but can not divided by 100. For example 1996 is jus 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.
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("Input text is not a number."); }finally { return ret; } } }
When run 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 related messages to show whether the year is a leap year or not.