Assignment Operators

Code Bar
= Simple Assignment
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
%= Modulo Assignment

The first and by far most important assignment operator is the simple assignment. It is the simplest assignment operator and works for every type of variable. It assigns the value on the right into the variable on the left. Here are some examples of it in use:

    boolean trueOrFalse = false;

    int x = 4;

    String hello = "helloWorld";

The other assignment operators are called compound assignment operators. They work exclusively on numerical variables, because each assignment statement performs a numerical operation. The addition assignment adds the value on the right to the variable on the left. The subtraction assignment subtracts the value on the right from the variable on the left.

For example the code written below will output 8 three times.

    int x = 4;  // 4                ASSIGNMENT

    x += 4;     // 4 + 4 = 8        ADDITION

    System.out.println(x); // 8

    x += 8;     // 8 + 8 = 16       ADDITION

    x /= 2;     // 16 / 2 = 8       DIVISION

    System.out.println(x); // 8

    x *= 3;     // 8 * 3 = 24       MULTIPLICATION

    x -= 16;    // 24 - 16 = 8      SUBTRACTION

    System.out.println(x); // 8

Since compound assignment operators only perform numerical operations on existing numbers, they cannot serve as initialization statements. The following code will throw an error because the computer is trying the add 5 to a non-existent number.

    int x;

    x += 5;

    System.out.println(x);

Lesson Quiz

What is the output of the below code blocks?

    int x = 9;

    x %= 2;

    x *= 5;

    System.out.println(x);
a. 2
b. 3
c. 5
d. 7
    int x = 4;

    x *= 5;

    x = 3;

    System.out.println(x);
a. 2
b. 3
c. 5
d. 7
    int x = 3;

    x -= 1;

    x *= 5;

    System.out.println(x);
a. 5
b. 7
c. 9
d. 10

Written by Jason Zhang

Notice any mistakes? Please email us at [email protected] so that we can fix any inaccuracies.