Java Program to Check Leap Year
What is a Calendar class?
In this Article, we will write a Program to Check Leap Year in Java.
The Calendar class in the Java programming language is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
Calendar Class:
The Calendar class also provides a number of methods for adding or subtracting time from a calendar, such as add() and roll(), and for comparing two calendars.
Java Program to Check Leap Year:
import java.util.*; public class Main{ public static void main(String[] args){ // Scanner class for taking input Scanner input = new Scanner(System.in); System.out.print("Enter a year: "); int year = input.nextInt(); // Initializing the answer variable boolean isLeapYear = false; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { isLeapYear = true; } } else { isLeapYear = true; } } if (isLeapYear) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } }
Input:
Enter a year: 1900
Output:
1900 is not a leap year.
Explanation:
In the above program,we first take input from the user for the year to be checked. Then, we use a series of if statements to check whether the year is divisible by 4, 100, and 400 to determine whether it is a leap year. Finally, we print out the result of whether the given year is a leap year or not.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment