Java Program to check if a Given Year is a Leap Year

Learn how to check if a given year is a leap year in Java using Scanner class, modulus operator, conditional statements.
A leap year is a year that contains 366 days and is divisible by 4, except years divisible by 100 unless they are also divisible by 400.
 
Code Explanation (Step-by-Step)
 
• Create a Scanner class object to accept user input.
• Use the sc.nextInt() method to read an integer value entered by the user and store it in the variable year. 
• The following condition is used to check whether the year is a leap year:
   if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) 
  •  year % 4 == 0 checks whether the year is divisible by 4. 
  • year % 100 != 0 checks whether the year is not divisible by 100. 
  • year % 400 == 0 checks whether the year is divisible by 400. 
  • If the year satisfies either of the following conditions:
    • It is divisible by 4 and not divisible by 100, or
    •  It is divisible by 400,
      then the year is a leap year.
• Otherwise, the program displays that the entered year is not a leap year. 
• Now the sc.close() method is used to close the Scanner object and release system resources.
				
					import java.util.Scanner;

public class LeapYearCheck {
	public static void main(String[] args) {
		System.out.println("Enter the year:");
		
		Scanner sc = new Scanner(System.in);
		int year = sc.nextInt();

		if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
			System.out.println("Leap year");
		} else {
			System.out.println("Not leap year");
		}

		sc.close();
	}
}
				
			

Output :
Enter the year:
2012
Leap year

Java 8 Program to Check Leap Year

				
					import java.util.Scanner;
import java.util.function.Predicate;

public class LeapYearCheck {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the year:");
        int year = sc.nextInt();

        Predicate<Integer> isLeapYear = y ->
                (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);

        if (isLeapYear.test(year)) {
            System.out.println("Leap year");
        } else {
            System.out.println("Not leap year");
        }

        sc.close();
    }
}