Divide Two Numbers in Java
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.
Java Program
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
Core Logic
The / operator between two int values performs integer division, keeping only the whole-number part of the result.
- 1
aholds20andbholds4. - 2
a / bevaluates to5, since 20 divides evenly by 4. - 3The result is stored in
quotientand printed with a label.
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
Approach 2: Java 8
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
Core Logic
Division slots into the same IntBinaryOperator pattern — the / operator's behavior gets wrapped in a lambda instead of written inline.
- 1
IntBinaryOperator divide = (x, y) -> x / y;stores the integer-division logic as a lambda. - 2
divide.applyAsInt(a, b)runs it withaandb, truncating any remainder exactly like the inline/did. - 3The result is printed the same way as the direct version.
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
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.