Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Conditional Statement Exercises: 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 user and print whether that year 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.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe