Multiply two numbers without using arithmetic operators in java

Let’s learn multiply two numbers without using arithmetic operators in java.

Multiply two numbers without using arithmetic operators in java

We can multiply two numbers without using arithmetic operators.

import java.util.Scanner;
public class MultiplyWithoutArithmeticOperators
{
   static int multiplyNumber(int num1, int num2)
   {
      int output = 0;
      boolean boolNegative = (num1 < 0 && num2 >= 0) || (num2 < 0 && num1 >= 0);
      boolean boolPositive = !boolNegative;
      num1 = Math.abs(num1);
      for(int a = 0; a < num1; a++)
      {
         if(boolNegative && num2 > 0 || boolPositive && num2 < 0)
         {
            output -= num2;
         }
         else
         {
            output += num2;
         }
      }
      return output;
   }
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter first number: ");
      int num1 = sc.nextInt();
      System.out.print("Please enter second number: ");
      int num2 = sc.nextInt();
      System.out.println("Multiplication of two numbers: " + multiplyNumber(num1, num2));
      sc.close();
   }
}


Output:

Please enter first number: 8
Please enter second number: 5
Multiplication of two numbers: 40


Also read – polymorphism in java