Compound Assignment Operators

Compound Assignment Operators

  • Compound assignment operators provide a shortcut to update the value of a variable.
  • These operators combine an operation (such as addition or multiplication) with assignment in a single step.

General Syntax

  • The general syntax is variable operator= expression; .
  • The variable is updated based on the operator and the expression.

Types of Compound Assignment Operators

  • The compound assignment operators in Java include: +=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<= and >>>=.

Understanding the Operators

  • The += operator adds the value at the right to the current value of the variable on the left and assigns the result to the variable on the left.
  • The -= operator subtracts the value at the right from the current value of the variable on the left and assigns the result to variable on the left.
  • The *= operator multiplies the current value of the variable on the left by the value at the right and assigns the result to the variable on the left.
  • The /= operator divides the current value of variable on the left by the value at the right and assigns the quotient to the variable on the left.
  • The %= operator divides the current value of variable on the left by the value at the right and assigns the remainder to the variable on the left.
  • The &=, |=, ^=, >>=, <<= and >>>= operators perform bitwise operations, which may be beyond the scope of this AP study guide.

Examples

  • x += 5; is equivalent to x = x + 5;.
  • y *= 2; is equivalent to y = y * 2;.
  • z /= 10; is equivalent to z = z / 10;.