Java Subtraction

Java Subtraction Arithmetic operator takes two operands as inputs and returns the difference of right operand from left operand.

- symbol is used for Subtraction Operator.

Syntax

Following is the syntax for Subtraction Operator.

</>
Copy
result = operand_1 - operand_2

The operands could be of any numeric datatype.

If the two operands are of different datatypes, implicit datatype promotion takes place and value of lower datatype is promoted to higher datatype.

Examples

1. Subtract with two Integers

In the following example, we shall take two integers and apply Subtraction.

Java Program

</>
Copy
public class SubtractionExample {
	public static void main(String[] args) {
		int a = 8;
		int b = 3;
		
		int result = a - b;
		System.out.print(result);
	}
}

Output

5

2. Subtraction with two numbers of different datatypes

In the following example, we shall find the difference of an integer and a float using Subtraction Arithmetic Operator.

As the operand values are of two different datatypes, Java promotes the value with lower datatype to higher datatype and the result would be of higher datatype. In the following example, int is promoted to float, and the result is a floating point number.

Java Program

</>
Copy
public class SubtractionExample {
	public static void main(String[] args) {
		int a = 8;
		float b = 3.5f;
		
		float result_1 = a - b;
		
		System.out.println(result_1);
	}
}

Output

4.5

Conclusion

In this Java Tutorial, we learned how to use Java Subtraction Operator.