This blog will demonstrate the approaches to multiplying two numbers in Java.
How to Multiply Two Numbers in Java?
The arithmetic operator “*” is used to multiply two numbers in Java. This operator can be placed between the operands and return the corresponding multiplication.
Example 1: Multiply Two Integers in Java
In this example, the two specified integers can be multiplied and returned:
int num2 = 2;
int result = num1 * num2;
System.out.println("The multiplication of the numbers is: "+result);
In the above lines of code, initialize the two integer values and apply the arithmetic operator “*” to multiply the specified integers. Lastly, display the resultant computed value.
Output
In the output, it can be implied that the corresponding multiplication is returned.
Example 2: Multiply Two Floats in Java
In this particular program, the arithmetic operator “*” can be utilized to multiply the two specified float values:
double num2 = 3.5;
double result = num1 * num2;
System.out.println("The multiplication of the numbers is: "+result);
In the above code snippet, initialize the two float values by specifying the type as “double”. After that, multiply the float values and display the resultant float value on the console.
Output
Example 3: Multiply User-defined Numbers in Java
The “nextInt()” method scans the next input token as an integer. In the below example, the multiplication of the two user input numbers can be carried out.
Firstly, make sure to include the below-provided library before heading to the example:
Now, let’s add the following code in the “main()” method:
In the above code block, apply the following steps:
- First, create a “Scanner” object” using the “new” keyword and the “Scanner()” constructor, respectively.
- The “System.in” parameter takes the input from the user.
- Now, input two numbers from the user. The associated “nextInt()” method ensures that the user input numbers are in the form of integers.
- Lastly, multiply the input numbers via the arithmetic operator “*” and display the computed multiplication.
Output
From this outcome, it can be analyzed that the user-defined numbers are evaluated appropriately.
Conclusion
The arithmetic operator “*” is utilized to multiply two numbers in Java. These numbers can be integer, float, or user-input numbers. This operator can be applied by placing it between the operands and returning the multiplication. This blog discussed the approaches to multiplying two numbers in Java.