Languages
[Edit]
EN

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

12 points
Created by:
Root-ssh
7645

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
}

Reading:
// In mathematics
https://en.wikipedia.org/wiki/Modular_arithmetic
// In computing
https://en.wikipedia.org/wiki/Modulo_operation
// Even and Odd numbers
https://en.wikipedia.org/wiki/Parity_(mathematics)

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join