Java Program to Multiply Two Numbers
Java multiplies numbers with the * operator: product = first * second. This page multiplies whole and decimal numbers, reads them from the user, and shows how to catch results that are too large for their type.
1. Multiply Two Numbers Using a Method
The multiply() method takes two double values, so it works for both whole and decimal numbers.
public class MultiplyNumbers {
static double multiply(double a, double b) {
return a * b;
}
public static void main(String[] args) {
System.out.println("20 x 40 = " + multiply(20, 40));
System.out.println("10.5 x 20.75 = " + multiply(10.5, 20.75));
System.out.println("-6 x 7 = " + multiply(-6, 7));
}
}
Output
20 x 40 = 800.0 10.5 x 20.75 = 217.875 -6 x 7 = -42.0
2. Multiply Two Numbers with User Input
import java.util.Scanner;
public class MultiplyNumbersInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double first = scanner.nextDouble();
System.out.print("Enter second number: ");
double second = scanner.nextDouble();
scanner.close();
System.out.println("Product: " + (first * second));
}
}
Output (with sample input)
Enter first number: 20.50 Enter second number: 50.75 Product: 1040.375
3. Detect Overflow with Math.multiplyExact()
Multiplying two large int values can overflow and silently give a wrong answer. Math.multiplyExact() throws an ArithmeticException instead, so the error is not hidden.
public class MultiplyExact {
public static void main(String[] args) {
int a = 100_000;
int b = 50_000;
System.out.println("a * b with int: " + (a * b)); // overflows
System.out.println("a * b with long: " + ((long) a * b)); // correct
try {
System.out.println(Math.multiplyExact(a, b));
} catch (ArithmeticException e) {
System.out.println("multiplyExact: " + e.getMessage());
}
}
}
Output
a * b with int: 705032704 a * b with long: 5000000000 multiplyExact: integer overflow
4. Summary
- Use the
*operator to multiply numbers of any numeric type. - A method with
doubleparameters handles both whole and decimal numbers. - Products grow fast: cast to
longbefore multiplying largeintvalues. Math.multiplyExact()throws an exception instead of returning an overflowed value.
Related Programs
Was this tutorial helpful?