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

Multiply Two Numbers in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

Multiplying two numbers with the * operator scales one value by another.

Given two integers, multiply them and print the result.

Input
6, 7
Output
Product: 42

Java Program

Java
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

Product: 42

Core Logic

The * operator multiplies two int values directly, producing their product in a single expression.

How It Works
  1. 1a holds 6 and b holds 7.
  2. 2a * b evaluates to 42, the product of the two values.
  3. 3The result is stored in product and printed with a label.
With 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

* operatorintarithmetic

Approach 2: Java 8

Java
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

Product: 42

Core Logic

Multiplication fits the same IntBinaryOperator shape as addition and subtraction — the operator itself becomes a value that can be passed around.

How It Works
  1. 1IntBinaryOperator multiply = (x, y) -> x * y; stores the multiplication logic as a lambda.
  2. 2multiply.applyAsInt(a, b) calls the lambda, returning the same result a * b would inline.
  3. 3The result is printed with the same label as the direct version.
With 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

IntBinaryOperatorfunctional interfacelambda expression

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.

Learn the Concept

Related Programs