In this tutorial we are going to learn how to Write a java program that takes two numbers as input and display the sum of two numbers. First, we try to solve this program using Scanner class which helps to accept user input and find the product of those numbers and print the result. Usually, we use "*" operator but in the second approach, we find the product without using "*" operator.
Multiplication of two numbers in java using scanner
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the First Number:");
//Read the input number
int firstNumber = scanner.nextInt();
System.out.println("Enter the Second Number:");
int secondNumber = scanner.nextInt();
//Closing the Scanner class object after the use
scanner.close();
//product of two Numbers
int productOfNumbers = firstNumber * secondNumber;
//Print the result
System.out.println("Product of Two Number: "+productOfNumbers);
}
}
Output:
Enter the First Number:
10
Enter the Second Number:
2
Product of Two Number: 20
Multiply two numbers without using operator in java
In this program we solve multiply two numbers without using Arithmetic operator(*) in Java
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int number1, number2, sum = 0;
System.out.print("Enter the first number: ");
number1 = scanner.nextInt();
System.out.print("Enter the second number: ");
number2 = scanner.nextInt();
//executes until the condition becomes false
for (int i = 1; i <= number1; i++) {
//calculates the sum
sum = sum + number2;
}
//prints the result
System.out.println("The multiplication of " + number1 + " and " + number2 + " is: " + sum);
}
}
Output:
Enter the first number: 12
Enter the second number: 5
The multiplication of 12 and 5 is: 60