w3resource

Java: Test a year is a leap year or not

Java Conditional Statement: Exercise-9 with Solution

Write a Java program that takes a year from the user and prints whether it is a leap year or not.

Test Data
Input the year: 2016

Pictorial Presentation:

Java conditional statement Exercises: Test a year is a leap year or not

Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise9 {

    
  public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Input the year: ");
        int year = in.nextInt();

        boolean x = (year % 4) == 0;
        boolean y = (year % 100) != 0;
        boolean z = ((year % 100 == 0) && (year % 400 == 0));

        if (x && (y || z))
        {
            System.out.println(year + " is a leap year");
        }
        else
        {
            System.out.println(year + " is not a leap year");
        }
    }
}

Sample Output:

Input the year: 2016                                                                                          
2016 is a leap year

Flowchart:

Flowchart: Java Conditional Statement Exercises - Test a year is a leap year or not

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program that takes the user to provide a single character from the alphabet. Print Vowel of Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.
Next: Write a program in Java to display the first 10 natural numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.