Write Java program to Perform subtraction without using minus (-) operator


This is a Java program that demonstrates how to perform subtraction without using the minus (-) operator.

  • The program first declares three integer variables num1, num2, and sub and initializes them to 0.
  • It then prompts the user to enter two integers num1 and num2 using the nextInt() method of the Scanner class.
  • To perform subtraction without using the minus operator, the program uses the bitwise complement operator (~) and the addition operator (+).
  • First, the program calculates the bitwise complement of num2 using the ~ operator. The bitwise complement of a number is the bitwise inversion of the number (i.e., each 0 bit becomes 1, and each 1 bit becomes 0).
  • Next, it adds the complement of num2 to num1 and adds 1 to get the result of the subtraction. This works because the complement of num2 is equal to -num2 - 1. Therefore, num1 + ~num2 + 1 is equivalent to num1 - num2.
  • The resulting value is stored in the sub variable, which is then output to the console using the printf() method.

Note that this method of subtraction is not as efficient as using the minus operator, as it involves several bitwise operations and addition. It is provided here as an example of how to perform arithmetic operations using bitwise operators.

Source Code

import java.util.Scanner;
public class Subtract_WithoutMinus
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int num1 = 0, num2 = 0,sub = 0;
 
		System.out.printf("Enter the Number 1 : ");
		num1 = input.nextInt();
		System.out.printf("Enter the Number 2 : ");
		num2 = input.nextInt();
 
		sub = num1 + ~num2 + 1;
		System.out.println("Subtraction without using Minus(-) Operator..");
		System.out.printf("Subtraction of %d - %d = %d", num1, num2, sub);
	}
}

Output

Enter the Number 1 : 23
Enter the Number 2 : 18
Subtraction without using Minus(-) Operator..
Subtraction of 23 - 18 = 5