Java Compound Assignment Operators

In this chapter you will learn:

  1. What are Arithmetic Compound Assignment Operators
  2. Syntax for Arithmetic Compound Assignment Operators
  3. Example - 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  ww.ja v a2 s. c o  m*/
  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:

Next chapter...

What you will learn in the next chapter:

  1. When to use Increment and Decrement Operator
  2. Different between Increment and Decrement Operator
  3. Example - increment operator
Home »
  Java Tutorial »
    Java Langauge »
      Java Operator
Java Arithmetic Operators
Java Compound Assignment Operators
Java Increment and Decrement Operator
Java Logical Operators
Java Logical Operators Shortcut
Java Relational Operators
Java Bitwise Operators
Java Left Shift Operator
Java Right Shift Operator
Java Unsigned Right Shift
Java ternary operator