Search code examples
javaif-statementreturnbooleanleap-year

Calculate Leap Year in Java is bypassing an else statement


There must be a bug somewhere in my 30 lines of code but I cannot find it and it's driving me nuts.

If I execute this code using isLeapYear(2004) I receive a true:

public class LeapYear {

    public static void main(String[] args) {
        isLeapYear(2004);
    }

    public static boolean isLeapYear (int year) {
        boolean status = true;

        if (year >= 0 || year <= 9999) {
            if (year % 4 == 0){
                status = true;
                System.out.println("true");
            } else if (year % 100 == 0){
                status = true;
                System.out.println("true");
            } else if (year % 400 == 0) {
                status = true;
                System.out.println("true");
            } else {
                status = false;
                System.out.println("false");
            }

        } else if (year < 0 || year > 9999){
            status = false;
            System.out.println("false");
        }
        return status;
    }
}

But if I run it for isLeapYear(-1200) it returns me a true as well but it shouldn't.

Why is my code bypassing else if (year < 0 || year > 9999) ?


Solution

  • you just have to change your first if statement to :

    if (year >= 0 && year <= 9999) {

    -1200 was always lower than 9999 so it was always going through this condition because of the ||.