C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Demonstrate compound assignment operators (+=, -=, etc.)

public class CompoundAssignmentDemo {

    public static void main(String[] args) {

 

        int a = 20;

 

        System.out.println("Initial value of a: " + a);

 

        // += operator

        a += 5;   // a = a + 5

        System.out.println("After a += 5  → " + a);

 

        // -= operator

        a -= 3;   // a = a - 3

        System.out.println("After a -= 3  → " + a);

 

        // *= operator

        a *= 2;   // a = a * 2

        System.out.println("After a *= 2  → " + a);

 

        // /= operator

        a /= 4;   // a = a / 4

        System.out.println("After a /= 4  → " + a);

 

        // %= operator

        a %= 3;   // a = a % 3

        System.out.println("After a %= 3  → " + a);

    }

}

Output

OUTPUT :
Initial value of a: 20
After a += 5  → 25
After a -= 3  → 22
After a *= 2  → 44
After a /= 4  → 11
After a %= 3  → 2

Explanation

1. What are Compound Assignment Operators?

Compound assignment operators combine an arithmetic operation with assignment.

2. Operator Meaning Table

Operator

Equivalent Expression

+=

a = a + value

-=

a = a - value

*=

a = a * value

/=

a = a / value

%=

a = a % value

3. Step-by-Step Execution

Starting value:

a = 20

  1. a += 5 → 20 + 5 = 25
  2. a -= 3 → 25 − 3 = 22
  3. a *= 2 → 22 × 2 = 44
  4. a /= 4 → 44 ÷ 4 = 11
  5. a %= 3 → remainder of 11 ÷ 3 = 2

4. Why Use Compound Assignment?

✅ Shorter code
✅ Better readability
✅ Faster execution
✅ Commonly used in loops and counters