Arithmetic Compound Assignment Operators

Description

Statements like the following


a = a + 4;

can be rewritten as


a += 4;

Both statements perform the same action: they increase the value of a by 4.

Syntax

Any statement of the form


var = var op expression;

can be rewritten as


var op= expression;

Example

Here is a sample program that shows several op= operator assignments:

 
public class Main {
//from w w  w .  j  a  v  a 2s. c  om
  public static void main(String args[]) {
    int a = 1;
    int b = 2;
    int c = 3;

    a += 1;
    b *= 2;
    c += a * b;
    c %= 3;
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);

  }
}

The output of this program is shown here:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures