Languages
[Edit]
EN

Modulo in java - syntax, how to use it with examples

12 points
Created by:
Root-ssh
175450

Modulo operator in java:

%

Examples:
A lof of examples with println of each operation,
it will explain all doubts how it works.

System.out.println(0 % 3); // 0
System.out.println(1 % 3); // 1
System.out.println(2 % 3); // 2
System.out.println(3 % 3); // 0
System.out.println(4 % 3); // 1
System.out.println(5 % 3); // 2
System.out.println(6 % 3); // 0
System.out.println(7 % 3); // 1
System.out.println(8 % 3); // 2
System.out.println(9 % 3); // 0

modulo with negative numbers

System.out.println(-4 % 3); // -1
System.out.println(-3 % 3); //  0
System.out.println(-2 % 3); // -2
System.out.println(-1 % 3); // -1

compare - division vs modulo

// DIVISION:
System.out.println(19 / 20); // 0
System.out.println(20 / 20); // 1
System.out.println(21 / 20); // 1
System.out.println(40 / 20); // 2
System.out.println(41 / 20); // 2

// MODULO:
System.out.println(19 % 20); // 19
System.out.println(20 % 20); // 0
System.out.println(21 % 20); // 1
System.out.println(40 % 20); // 0
System.out.println(41 % 20); // 1

Check if number is even

int num = 2;
if ((num % 2) == 0) {
    System.out.println("even number"); // even number
}

Check if number is odd

int num = 1;
if ((num % 1) == 0) {
    System.out.println("odd number"); // odd number
}

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join