Skip to content
C

Assignment Operators

Assignment operators are used to store a value into a variable. The simplest one is =, but Java also provides shortcut versions like +=, -=, *=, and /= that combine a calculation with assignment in one step.


1. What are Assignment Operators?

Assignment operators are used to store a value into a variable. The simplest one is =, but Java also provides shortcut versions like +=, -=, *=, and /= that combine a calculation with assignment in one step.

2. Why is it used?

Shortcut assignment operators save time and make code shorter and cleaner, especially when you're repeatedly updating the same variable, such as adding points to a running score.

3. Real-Life Example

Think of a shop's running total on a bill. Each time an item is added, the cashier doesn't restart the calculation — they simply add the new item's price to the existing total. total += price does exactly this in one step.

4. Syntax

java
a = b; // assign a += b; // same as a = a + b a -= b; // same as a = a - b a *= b; // same as a = a * b a /= b; // same as a = a / b

5. Example Program

java
public class AssignmentDemo { public static void main(String[] args) { int total = 100; total += 50; // total becomes 150 total -= 20; // total becomes 130 System.out.println("Final Total: " + total); } }

Output:

Final Total: 130

6. Key Points to Remember

  • +=, -=, *=, /= are shortcuts that reduce repetitive code.
  • The variable on the left must already exist before using shortcut assignment on it.
  • These operators work with all numeric types, and += also works with String for joining text.

Mock Test

  • Assignment Operators - Quick Test

    10 questions on =, +=, -=, *=, /= and how compound assignment works.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems