You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

闰年判断Java代码解析:==0的含义与作用问询

Understanding the == 0 in Leap Year Java Code

Hey there! Let's break down that confusing == 0 part and the leap year logic step by step so everything clicks.

First: What does the % operator do?

In Java, % is the modulus operator—it calculates the remainder when you divide the first number by the second. For example:

  • 10 % 4 gives 2 (since 4×2=8, 10-8=2 left over)
  • 12 % 4 gives 0 (4×3=12, no remainder at all)

Why do we use == 0?

When we write year % 4 == 0, we're checking if dividing the year by 4 leaves no remainder. That's exactly what it means for a number to be perfectly divisible by another number—this is the core of our leap year rules.

Let's map this to the leap year conditions you mentioned:

  • Rule 1: A year is a leap year if it's divisible by 4 but not divisible by 100.
    • In code: year % 4 == 0 && year % 100 != 0
    • The != 0 here does the opposite: it checks if dividing by 100 does leave a remainder (so the year isn't a century year like 1900).
  • Rule 2: If a year is divisible by 400, it's a leap year (even if it's a century year).
    • In code: year % 400 == 0
    • This covers exceptions like 2000 (2000%400=0, so it's a leap year) but not 1900 (1900%400=300≠0, so it's not).

Putting it all together

The line boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; is just translating our two leap year rules into Java logic:

  • The && means "both conditions must be true"
  • The || means "either condition can be true"

Let's test some examples to make it concrete:

  • 2020: 2020%4=0 and 2020%100=20≠0 → returns true
  • 1900: 1900%4=0 but 1900%100=0 (so first condition fails), and 1900%400=300≠0 → returns false
  • 2000: 2000%400=0 → returns true

内容的提问来源于stack exchange,提问作者Tomas Bernatonis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:25:45