Java Arithmetic Operators Compound Assignment Operators

Introduction

Java Arithmetic Compound Assignment Operators can combine an arithmetic operation with an assignment.

For the following statement:

a = a + 4; 

In Java, you can rewrite this statement as shown here:

a += 4; 

This version uses the += compound assignment operator.

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

Here is another example,

a = a % 2; 

which can be expressed as

a %= 2; 

In this case, the %= obtains the remainder of a /2 and puts that result back into a.

There are compound assignment operators for all of the arithmetic, binary operators.

Any statement of the form


var = var op expression; 

can be rewritten as

var op= expression; 

The following code shows several op= assignments:

// Demonstrate several assignment operators.
public class Main {
  public static void main(String args[]) {
    int a = 1;//from  www.  j  a v  a2s  .c o m
    int b = 2;
    int c = 3;

    a += 5;
    b *= 4;
    c += a * b;
    c %= 6;
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);
  }
}



PreviousNext

Related