📝 Assignment & Compound Operators

Last Updated: Jan 2026


What is Assignment (=)?

  • The assignment operator (=) is used to store a value in a variable.
  • It assigns the value on the right side to the variable on the left side.

Example:

int x = 10; // x holds 10
int y = 5; // y holds 5

Compound Operator

Compound assignment operators combine an operation and assignment in one step.

  • Instead of writing x = x + 5, you can write x += 5.
  • They work for arithmetic and bitwise operations.
OperatorMeaningEquivalent Long Form
=Assignx = 10
+=Add and assignx += 5 → x = x + 5
-=Subtract and assignx -= 3 → x = x - 3
*=Multiply and assignx *= 2 → x = x * 2
/=Divide and assign (float result) x /= 4 → x = x / 4
%=Modulus and assignx %= 3 → x = x % 3
&=Bitwise AND and assignx &= 3 → x = x & 3
|=Bitwise OR and assignx |= 2 → x = x | 2
^=Bitwise XOR and assignx ^= 4 → x = x ^ 4
<<=Left shift and assignx <<= 1 → x = x << 1
>>=Right shift and assignx >>= 2 → x = x >> 2

Example

int x = 10;

x += 5; // x = x + 5
println("%d\n",x);  // 15

x -= 3; // x = x - 3
println("%d\n",x);  // 12

x *= 2; // x = x * 2
println("%d\n",x);  // 24

x /= 4; // x = x / 4
println("%d\n",x);  // 6


x = 10; // binary: 1010
x &= 6; // 1010 & 0110 = 0010 (2)
println("%d\n",x);  // 2

x |= 4; // 0010 | 0100 = 0110 (6)
println("%d\n",x);  // 6

x ^= 3; // 0110 ^ 0011 = 0101 (5)
println("%d\n",x);  // 5

Tip: Compound operators save time and reduce typing. You'll use them a lot in loops, counters, and calculations .Don't worry! For Bitwise Operator ,We will cover in upcoming section.


💡 Quick Practice

  1. Create a variable count = 10 → add 5 using +=
  2. Subtract 2 using -= and print result
  3. Multiply by 3 using *=
  4. Divide by 2 using /=
  5. Print each result step-by-step in console

Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR