Wednesday, 24 June 2015

Java : How To Check Given Year Is Leap Year Or Not?

A Leap year is a year which contains one additional day, i.e instead of 365 days, it contains 366 days. So how do you check given number is Leap year or not?

A Leap year occurs for every 4 years. for example, Years 2000,2004,2008,2012,2016 are leap years. If you observer, you can find that these years are multiples of 4. So you may think, if we get remainder 0, when divided with 4, then it's leap year, else not a leap year.

But here, you also need to think about any exceptional cases, such as Years 1700,1800,1900 are not leap years even though, they are multiples of 4. So if a year is century i.e 1700,2000, you need to divide it with 400, and if remainder is 0, it is leap year, else not.

The algorithm looks like below.

if Year is divisible by 400 then
        it is leap year
else if Year is divisible by 100 then
        it is not a leap year
else if Year is divisible by 4 then
       it is leap year
else
       the Year is not a leap year.

Let's implement the above algorithm in Java.
public class LeapYear {
 
 public static void main(String[] args) {
  LeapYear ly = new LeapYear();
  ly.isLeapYear(1000);
  ly.isLeapYear(2000);
  ly.isLeapYear(2004);
  ly.isLeapYear(1008);
 }

 private void isLeapYear(int year) {
  if(year % 400 == 0) {
   System.out.println(year+" Is a Leap Year");
  } else if(year % 100 == 0) {
   System.out.println(year+" Is Not a Leap Year");
  } else if(year % 4 == 0) {
   System.out.println(year+" Is a Leap Year");
  } else {
   System.out.println(year+" Is Not a Leap Year");
  }
 } 
}

If you see the above code, we have multiple if - else if - else statements. We can write the same code in single if-else statement, like below. The if condition is, the year should divide with either 400 or 4 but not with 100.
private void isLeapYearv2(int year) {
  if((year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)) {
   System.out.println(year+" Is a Leap Year");
  } else {
   System.out.println(year+" Is Not a Leap Year");
  }
 }

Method 2:

To check the given number is Leap year or not, you can also use inbuilt Java API method. For that, you need to get an instance of GregorianCalender, and then call isLeapYear() method by passing, the year. The code is below.
private void isLeapYearv3(int year) {
  GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
  
  if(gc.isLeapYear(year)) {
   System.out.println(year+" Is a Leap Year");
  } else {
   System.out.println(year+" Is Not a Leap Year");
  }
 }



0 comments:

Post a Comment

Note: only a member of this blog may post a comment.