Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

72. Checking for a leap year

This problem becomes easy as long as we know what a leap year is. In a nutshell, a leap year is any year divisible by 4 (so, year % 4 == 0) that it is not a century (for instance, 100, 200, …, n00). However, if the year represents a century that is divisible by 400 (so, year % 400 == 0), then it is a leap year. In this context, our code is just a simple chain of if statements as follows:

public static boolean isLeapYear(int year) {
  if (year % 4 != 0) {
    return false;
  } else if (year % 400 == 0) {
    return true;
  } else if (year % 100 == 0) {
    return false;
  }
  return true;
}

But, this code can be condensed using the GregorianCalendar as well:

public static boolean isLeapYear(int year) {
  return new GregorianCalendar(year, 1, 1).isLeapYear(year);
}

Or, starting with JDK 8, we can rely on the java.time.Year API as follows:

public static boolean isLeapYear(int year) {
  return Year.of(year).isLeap(); 
}

In...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard