Java Addition

Java Addition Arithmetic operator takes two operands as inputs and returns the sum of numbers.

+ symbol is used for Addition Operator.

Syntax – Addition Operator

Following is the syntax for Addition Operator.

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.

ADVERTISEMENT

Example 1 – Add two Integers

In the following example, we shall add two integers using Addition Arithmetic Operator.

AdditionExample.java

public class AdditionExample {
	public static void main(String[] args) {
		int a = 8;
		int b = 3;
		
		int result = a + b;
		System.out.print(result);
	}
}

Output

11

Example 2 – Add two Values of Different Datatypes

In the following example, we shall add an integer and a floating point number using Addition Arithmetic Operator.

As we are adding values of two different datatypes, one with lower datatype promotes to higher datatype and the result is of higher datatype. In the following example, int would be promoted to float, and the result would be float.

If you would like to store the result in an int, you should typecast the result to int.

AdditionExample.java

public class AdditionExample {
	public static void main(String[] args) {
		int a = 8;
		float b = 3.5f;
		
		int result_1 = (int) (a + b); //typecast
		float result_2 = a + b; //implicit type promotion
		
		System.out.println(result_1);
		System.out.println(result_2);
	}
}

Output

11
11.5

Conclusion

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