Top community members

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

[Edit]
EN

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

12 points
Created by:
Root-ssh
5171

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)

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more