Multiply Two Numbers in Java
Problem
Multiplying two numbers with the * operator scales one value by another.
Given two integers, multiply them and print the result.
Java Program
public class MultiplyTwoNumbers {
public static void main(String[] args) {
int a = 6;
int b = 7;
int product = a * b;
System.out.println("Product: " + product);
}
}Output
Core Logic
The * operator multiplies two int values directly, producing their product in a single expression.
- 1
aholds6andbholds7. - 2
a * bevaluates to42, the product of the two values. - 3The result is stored in
productand printed with a label.
a = 6 and b = 7, a * b evaluates to 42, so the program prints "Product: 42".Key Point: Multiplying two large int values can overflow the 32-bit int range silently — use long when the product might exceed about 2.1 billion.
Key Concepts
Approach 2: Java 8
import java.util.function.IntBinaryOperator;
public class MultiplyTwoNumbersLambda {
public static void main(String[] args) {
int a = 6;
int b = 7;
// The multiplication logic is stored as a lambda, callable like any value
IntBinaryOperator multiply = (x, y) -> x * y;
int product = multiply.applyAsInt(a, b);
System.out.println("Product: " + product);
}
}
Output
Core Logic
Multiplication fits the same IntBinaryOperator shape as addition and subtraction — the operator itself becomes a value that can be passed around.
- 1
IntBinaryOperator multiply = (x, y) -> x * y;stores the multiplication logic as a lambda. - 2
multiply.applyAsInt(a, b)calls the lambda, returning the same resulta * bwould inline. - 3The result is printed with the same label as the direct version.
a = 6 and b = 7, multiply.applyAsInt(6, 7) returns 42.Key Point: The same overflow risk from the direct * version still applies here — wrapping the operation in a lambda changes how it's called, not the underlying int arithmetic.
Key Concepts
Interview Questions
How do you detect overflow when multiplying?
Math.multiplyExact(a, b) throws an ArithmeticException if the result doesn't fit in an int.
Why might a product of two ints be wrong even when stored in a long?
long r = a * b; multiplies as int first, then widens the already-overflowed result. Cast first: (long) a * b.