java_logo

Subtraction without using ‘-‘ operator in Java

College Basic Programming Activity

Hi guys! I’m back and I’m going to share another programming problem and show the solution.
Problem:
Write a program which subtracts two integers without using minus (-) operator.

Solution:
Let’s use this algorithm:

a – b = a + -1 * b

Then, let’s convert to code:

public static void main(String[] args) {

     System.out.println("Difference of 5 and 3 is: " + sub(5,3));

}

public static int sub(int x, int y) {

     int diff = 0;
		
     diff = x + (-1 * y);
		
     return diff;
		
}

Result:
Difference of 5 and 3 is: 2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.