Monday, 6 January 2014

Java - How to Calculate Leap Year


A leap year is a year that has 366 days i.e; one day extra. 

Algorithm 

To determine whether a year is leap year or not, use the following algorithm.

If year is divisible by 400 
    then is_leap_year else if year is divisible by 100 
    then not_leap_year else if year is divisible by 4 
    then is_leap_year else not_leap_year
 

Java Code


public class LeapYearExample {
 
    public static void main(String[] args) {
 
 LeapYearExample lye = new LeapYearExample();
 System.out.println("1993 is a leap year : " + lye.isLeapYear(1993));
 System.out.println("2020 is a leap year : " + lye.isLeapYear(2020));
 System.out.println("2050 is a leap year : " + lye.isLeapYear(2050));
 
    }
 
    public boolean isLeapYear(int year) {
 
 if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
  return true;
 } else {
  return false;
 }
    }
 
}

Output

1993 is a leap year : false
2020 is a leap year : true
2050 is a leap year : false


References

1. Wikipedia : Leap Year
2. Maven Scientists Code Library



Related Tutorials :

Usage of this keyword in Java - Java SE

Operators in Java - Maven Scientists Course Ebook (Free Download)

Expressions Statements and Blocks in Java - Maven Scientists Course Ebook (Free Download)
Exceptions in Java - Detailed Explanation


Get Ebooks delivered to your email id

Comments

Subscribe to our channel

Facebook

Powered by Blogger.

Home | Contact Us | DMCA | Terms of Service | Privacy | Advertise

Maven Scientists