Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (1.5k points)

I am studying a book called as "The Art and Science of Java" and it shows how to calculate a leap year. 

The book uses ACM Java Task Force's library.

Here is the code the books uses

import acm.program.*;

public class LeapYear extends ConsoleProgram {
    public void run()
    {

        println("This program calculates leap year.");
        int year = readInt("Enter the year: ");     

        boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));

        if (isLeapYear)
        {
            println(year + " is a leap year.");
        } else
            println(year + " is not a leap year.");
    }

}

I have modified the code a little bit and here is the code:

import acm.program.*;

public class LeapYear extends ConsoleProgram {
    public void run()
    {

        println("This program calculates leap year.");
        int year = readInt("Enter the year: ");

        if ((year % 4 == 0) && year % 100 != 0)
        {
            println(year + " is a leap year.");
        }
        else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
        {
            println(year + " is a leap year.");
        }
        else
        {
            println(year + " is not a leap year.");
        }
    } 

} 

 I just wanted to know that which is the best code? Is there any code snippet alternative to that?

1 Answer

0 votes
by (1.4k points)

Below is the code to check whether given leap year is not 

public static boolean checkforLeapYear(int year) { 

  Calendar cal = Calendar.getInstance(); 

  cal.set(Calendar.YEAR, year); 

  return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; 

} 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 6, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...