Search code examples
javaloopsbreakcontinue

what does x % 2 > 0 mean in java?


I'm currently learning java in my online classes and I'm learning about loops (specifically continue and break statements). The example given to me was:

int j = 0
while (true){
    System.out.println();
    j++;
    System.out.print(j);
    if (j%2 > 0) continue
    System.out.print(" is divisible by 2");
    if (j >= 10) break;
}

I don't understand why its (j%2 > 0) and not (j%2 == 0) because what if 'j' is 5 for example and you do 5%2. Wouldnt the number you get be 1? Or am I missing something? Can someone please explain this to me? (sorry is I'm not my question is a little confusing. I've never used this site before and I'm pretty young)


Solution

  • Continue means "go to the top of the loop, skipping the rest of the loop's code" not "continue with the code". So since 5%2 is 1, and 1 > 0, the continue will execute, going directly to the top of the loop and skipping the rest of the body.

    Why do they use > 0 instead of != 0? There isn't any technical reason, its a style difference. I personally would have used the latter as its more clear in my mind. But either works.