Java Programs›Basics & I/O›Divide Two Numbers

Divide Two Numbers in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

Dividing two int values in Java performs integer division, discarding any remainder.

Given two integers, divide the first by the second and print the result.

Input
20, 4
Output
Quotient: 5

Java Program

Java
public class DivideTwoNumbers { public static void main(String[] args) { int a = 20; int b = 4; int quotient = a / b; // integer division — no fractional part System.out.println("Quotient: " + quotient); } }

Output

Quotient: 5

Core Logic

The / operator between two int values performs integer division, keeping only the whole-number part of the result.

How It Works
  1. 1a holds 20 and b holds 4.
  2. 2a / b evaluates to 5, since 20 divides evenly by 4.
  3. 3The result is stored in quotient and printed with a label.
With a = 20 and b = 4, a / b evaluates to 5, so the program prints "Quotient: 5".
💡

Key Point: int division truncates any remainder — 7 / 2 gives 3, not 3.5. Use double values (or a cast) when a fractional result is needed.

Key Concepts

/ operatorinteger divisionint

Approach 2: Java 8

Java
import java.util.function.IntBinaryOperator; public class DivideTwoNumbersLambda { public static void main(String[] args) { int a = 20; int b = 4; // Integer division still truncates the same way inside the lambda body IntBinaryOperator divide = (x, y) -> x / y; int quotient = divide.applyAsInt(a, b); System.out.println("Quotient: " + quotient); } }

Output

Quotient: 5

Core Logic

Division slots into the same IntBinaryOperator pattern — the / operator's behavior gets wrapped in a lambda instead of written inline.

How It Works
  1. 1IntBinaryOperator divide = (x, y) -> x / y; stores the integer-division logic as a lambda.
  2. 2divide.applyAsInt(a, b) runs it with a and b, truncating any remainder exactly like the inline / did.
  3. 3The result is printed the same way as the direct version.
With a = 20 and b = 4, divide.applyAsInt(20, 4) returns 5.
💡

Key Point: The lambda body is still ordinary integer division — dividing by 0 would still throw an ArithmeticException inside applyAsInt(), so this doesn't add any safety over the inline version.

Key Concepts

IntBinaryOperatorfunctional interfacelambda expression

Interview Questions

What happens when you divide an int by zero?

It throws ArithmeticException: / by zero. Dividing a double by zero gives Infinity instead.

How do you get the decimal result of two ints?

Cast one of them: (double) a / b.

Learn the Concept

Related Programs