Java - Compound Arithmetic Assignment Operators

What are Compound Operators?

The basic arithmetic operators (+, -, *, /, and %) has a corresponding compound arithmetic assignment operator.

A compound arithmetic assignment operator is used in the following form:

operand1 op= operand2 
  • op is one of the arithmetic operators (+, -, *, /, and %).
  • operand1 and operand2 are of primitive numeric data types
  • operand1 must be a variable.

The above expression is equivalent to the following expression:

operand1 = (Type of operand1) (operand1 op operand2) 

Example

Suppose you have two variables, num1 and num2.

  
int num1 = 100; 
byte num2 = 15; 
  

To add the value of num1 to num2 together, write code as

num2 = (byte)(num2 + num1); 
  

The code above can be rewritten using the compound arithmetic operator += as follows:

  
num2 += num1; // Adds the value of num1 to num2 
  

For example,

int i = 100; 
i += 5.5; // Assigns 105 to i 

is equivalent to

i = (int)(i + 5.5); // Assigns 105 to i 

Demo

public class Main {
  public static void main(String[] args) {
    int i = 110; 
    float f = 120.2F; 
      /*from   w w w  .j  ava2s. co m*/
    i += 10;  
    System.out.println(i);
    i -= 15;  
    System.out.println(i);
    i *= 2;   
    System.out.println(i);
    i /= 2;   
    System.out.println(i);
    i /= 0;   
    System.out.println(i);
    f /= 0.0; 
    System.out.println(f);
    i %= 3;   
    System.out.println(i);
  }
}

Result

+= on String variables

The compound assignment operator += can be used on String variables.

operand1 must be of type String and the operand2 may be of any type. Only the += operator can be used with a String left-hand operand. For example,

String str1 = "Hello"; 
str1 = str1 + 100;  // Assigns "Hello100" to str1 

can be rewritten as

str1 += 100; // Assigns "Hello100" to str1  

Demo

public class Main {
  public static void main(String[] args) {
    String str = "Hello"; 
    float f = 120.2F; 
    byte b = 5; // ww  w. j  a  va 2s.com
    str += " How are you?";
    System.out.println(str);
    str += f;  
    System.out.println(str);
    str += b;   
    System.out.println(str);
  }
}

Result

boolean Promotion

boolean type cannot be used with += unless left-hand operand (i) is a String variable.

int i = 1; 
boolean b1 = true; 
i += b1; // A compile-time error.