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:
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:
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework