Java/Language Basics/Modulus
Detect even/odd number with the modulus operator.
<source lang="java">
public class Main {
public static void main(String[] argv) { int x = 5; if (x % 2 == 0) { System.out.println("even"); } if (x % 2 != 0) { System.out.println("odd"); } // ... or binary AND operator... if ((x & 1) == 0) { System.out.println("even"); } if ((x & 1) != 0) { System.out.println("odd"); } }
}
</source>
Modulus Operator Example
<source lang="java">
public class Main {
public static void main(String[] args) { int i = 5; double d = 2; System.out.println("i mod 10 = " + i % 10); System.out.println("d mod 10 = " + d % 10); }
} /* i mod 10 = 5 d mod 10 = 2.0
- /
</source>