Java Tutorial
🔍
Java ProgramsBasics & I/OCalculate Remainder

Calculate Remainder in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

The modulo operator (%) returns the remainder left over after dividing one number by another.

Given two integers, find the remainder when the first is divided by the second.

Input
17, 5
Output
Remainder: 2

Java Program

Java
public class CalculateRemainder { public static void main(String[] args) { int a = 17; int b = 5; int remainder = a % b; // leftover after integer division System.out.println("Remainder: " + remainder); } }

Output

Remainder: 2

Core Logic

The % operator divides one number by another and returns just the leftover remainder, instead of the quotient.

How It Works
  1. 1a holds 17 and b holds 5.
  2. 2a % b evaluates to 2 — 5 goes into 17 three times (15), leaving 2 left over.
  3. 3The result is stored in remainder and printed with a label.
With a = 17 and b = 5, a % b evaluates to 2, so the program prints "Remainder: 2".
💡

Key Point: % is also the standard way to check divisibility or evenness in Java — n % 2 == 0 tests whether n is even.

Key Concepts

% operatormoduloint

Approach 2: Manual Calculation Without %

Java
public class CalculateRemainderManual { public static void main(String[] args) { int a = 17; int b = 5; int quotient = a / b; int remainder = a - (quotient * b); // same result as a % b System.out.println("Remainder: " + remainder); } }

Output

Remainder: 2

Core Logic

The remainder can also be derived manually from division and multiplication, without the % operator at all — useful for understanding what % actually computes under the hood.

How It Works
  1. 1a / b performs integer division first, giving the whole-number quotient — 17 / 5 is 3.
  2. 2Multiplying that quotient back by b (3 * 5 = 15) gives the largest multiple of b that fits inside a.
  3. 3Subtracting that from the original a (17 - 15) leaves exactly the remainder, 2.
For 17 and 5: quotient = 3, 3 * 5 = 15, and 17 - 15 = 2 — the same result % would give directly.
💡

Key Point: This is exactly the identity the % operator implements internally: a % b always equals a - (a / b) * b for positive integers.

Key Concepts

integer divisionarithmetic identity

Related Programs