I suspect 443 is the total number of Sundays in January in the twentieth century. This happens because you walk over all possible days of the twentieth century and then check if the current month is January and if the current day is Sunday.
This is not what you want.
I would use a different approach:
- Walk over the 1st day of each month of each year.
- And then check if it's a Sunday.
The code will probably be much faster.
// Each year
for (int y = 1901; y < 2001; y++) {
// Each month of the year
for (int m = 1; m <= 12; m++) {
if (LocalDate.of(y, m, 1).getDayOfWeek() == DayOfWeek.SUNDAY) {
count++;
}
}
}
Your code would have been correct if you changed date1.getMonth() == JANUARY to date1.getDayOfMonth() == 1. However, the method is very inefficient, because it checks each day of the twentieth century, while it only needs to check the first day of each month. The abovementioned code is approximately 40 times faster on my machine.
Here is an equivalent of the abovementioned code, with functional style:
long count = Stream.iterate(YearMonth.of(1901, 1), ym -> ym.plusMonths(1))
.takeWhile(ym -> ym.isBefore(YearMonth.of(2001, 1)))
.map(ym -> ym.atDay(1).getDayOfWeek())
.filter(DayOfWeek.SUNDAY::equals)
.count();
Using Todd's Java-TimeStream, with functional style:
YearMonthStream
.from(YearMonth.of(1901, 1))
.until(YearMonth.of(2000, 12))
.stream()
.map(ym -> ym.atDay(1).getDayOfWeek())
.filter(DayOfWeek.SUNDAY::equals)
.count();