Search code examples
javagregorian-calendar

Can you use variables when calling GergorianCalendar.isLeapYear()?


If I use:

GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
boolean yearIsLeapYear = cal.isLeapYear(2016);

Then my varialbe yearIsLeapYear is correctly set to true. However, if I use a variable in place of 2016 it doesn't not work.

int year = 2016;
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
boolean yearIsLeapYear = cal.isLeapYear(year);

Am I missing something or is it not possible to pass a variable into the isLeapyYear() method? In the program I'm writing the value in the year field can change depending on user input and the final algorithm I'm implementing needs to behave differently when the current year is a leap year or the next year is a leap year. I thought this would be simple way to perform the check.

Edit showing full code

Fields are:

private int year;
private boolean yearIsLeapYear , nextYearIsLeapYear, previousYearIsLeapYear;

I have a constructor as follows:

public FirstDayOfSummer(int currentYear) {
    year = currentYear;
    checkForLeapYears();
}

And the following method which I am calling in the constructor:

private void checkForLeapYears(){
    GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();

    //checking for a leap year using the current value of "year"
    if(cal.isLeapYear(year)){
        yearIsLeapYear = true;
    }
    else{
        yearIsLeapYear = false;
    }

    //checking for a leap year using the value of "year" + 1
    if(cal.isLeapYear(year + 1){
        nextYearIsLeapYear = true;
    }
    else{
        nextYearIsLeapYear = false;
    }

    //checking for a leap year using the value of "year" - 1
    if(cal.isLeapYear(year - 1){
        previousYearIsLeapYear = true;
    }
    else{
        previousYearIsLeapYear = false;
    }

}

Solution

  • The error was in calling my constructor.

    FirstDayOfSummer currentYearFirstDayOfSummer = new FirstDayOfSummer(Calendar.getInstance().get(Calendar.YEAR));
    currentYearFirstDayOfSummer.setYear(2015);
    

    I was accidently using the current year in the constructor and then trying to use a mutator method to change it to something else. Because my method to check for a leap year was only being called in the constructor and not also in the mutator it was never updating my booleans!

    Thanks for asking good questions!