Java - Operator Addition Operator +

What is Addition Operator?

The addition operator (+) is used in the form

operand1 + operand2 
  

The addition arithmetic operator + adds two numeric values together.

The operands may be any numeric literals, numeric variables, numeric expressions, or method calls.

byte b1; 
b1 = 3 + 2;

Demo

public class Main {
  public static void main(String[] args) {
    byte b1; /*from w w  w  .ja  v  a 2s  .  com*/
    b1 = 3 + 2; 

    System.out.println(b1);

  }
}

Result

The compiler will check the range of results for constant values.

Demo

public class Main {
  public static void main(String[] args) {
    byte b1; /*from  ww  w .  j  a  v a  2s  .  c  o m*/
    b1 = 15 + 110; // Ok. 125 is in the range -128 and 127 

    System.out.println(b1);
    
    //b1 = 15 + 210; // Error. 225 is in the range -128 and 127 

  }
}

Result

Addition Operator Promotion

In the following code, i is promoted to int and i + 5 is of the data type int. int to byte assignment is not permitted.

byte b1 = 2;
int i = 10; 
// An error. 
b1 = i + 5;
b1 = (byte)(i + 5); // OK 

f1 is promoted to double and f1 + d1 is of the data type double

float f1 = 2.5F; 
double d1 = 20.0; 
f1 = f1 + d1; //An error.

i is promoted to float and i + f1 is of the data type float

float f1 = 2.5F; 
int i = 10; 
f1 = i + f1; // Ok. 

i is promoted to double and i + d1 is of data type double. double to float assignment is not permitted

double d1 = 20.0; 
int i = 10; 
float f1 = 2.5F; 
f1 = i + d1; // An error.

f1 = (float)(i + d1); // OK 
    

2.0 and 3.2 are of the type double. The result of 2.0 + 3.2 is 5.2, which is of the type double. double to float assignment is not permitted.

float f1 = 2.5F; 
f1 = 2.0 + 3.2; //An error. 

2.0F and 3.2F are of the type float. The result of 2.0F + 3.2F, which is 5.2F, is of the type float.

float f1 = 2.5F; 
f1 = 2.0F + 3.2F; // Ok.

j is promoted to float and f1 + j is of the data type float. float to double assignment is permitted.

int i = 10; 
float f1 = 2.5F; 
double d1 = f1 + i;     // Ok.