Home »
Java Programs »
Java Basic Programs
Java program to perform subtraction without using minus (-) operator
Input two numbers, write a Java program to perform subtraction without using minus (-) operator.
Submitted by Nidhi, on February 23, 2022
Problem statement
In this program, we will read two integer numbers from the user and perform subtraction without using the minus (-) operator, and print the result.
Source Code
The source code to perform subtraction without using the Minus (-) operator is given below. The given program is compiled and executed successfully.
// Java program to perform subtraction
// without using minus (-) operator
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner X = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
int sub = 0;
System.out.printf("Enter first number: ");
num1 = X.nextInt();
System.out.printf("Enter second number: ");
num2 = X.nextInt();
sub = num1 + ~num2 + 1;
System.out.printf("Subtraction of %d-%d=%d", num1, num2, sub);
}
}
Output
Enter first number: 65
Enter second number: 54
Subtraction of 65-54=11
Explanation
In the above program, we imported the "java.util.Scanner" package to read input from the user. Here, we created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we read two integer numbers from the user and performed the subtraction operation using "+" and "~" operators. After that, we printed the result.
Java Basic Programs »