Core Java Fundamentals ยท Operators

Assignment Operators

Learn how to assign and modify values of variables using basic and compound assignment operators.

AssignmentOperatorsDemo.java

public class AssignmentOperatorsDemo {
    public static void main(String[] args) {
        // Basic assignment operator =
        int num = 10;
        System.out.println("Initial value: " + num);

        // Add and assign operator +=
        num += 5; // equivalent to num = num + 5;
        System.out.println("After += 5: " + num);

        // Subtract and assign operator -=
        num -= 3; // equivalent to num = num - 3;
        System.out.println("After -= 3: " + num);

        // Multiply and assign operator *=
        num *= 2; // equivalent to num = num * 2;
        System.out.println("After *= 2: " + num);

        // Divide and assign operator /=
        num /= 4; // equivalent to num = num / 4;
        System.out.println("After /= 4: " + num);
    }
}

Step by step

  1. We declare an integer variable num and use the basic assignment operator = to assign it the value of 10.
  2. The current value of num (10) is printed to the console.
  3. The += (add and assign) operator adds 5 to the current value of num and assigns the result back to num. This is a shorthand for num = num + 5;. The value becomes 10 + 5 = 15.
  4. The new value of num (15) is printed.
  5. The -= (subtract and assign) operator subtracts 3 from num and assigns the result back. This is a shorthand for num = num - 3;. The value becomes 15 - 3 = 12.
  6. The new value of num (12) is printed.
  7. The *= (multiply and assign) operator multiplies num by 2. This is a shorthand for num = num * 2;. The value becomes 12 * 2 = 24.
  8. The new value of num (24) is printed.
  9. The /= (divide and assign) operator divides num by 4. This is a shorthand for num = num / 4;. The value becomes 24 / 4 = 6.
  10. The final value of num (6) is printed.