Operators

Java Program to Demonstrate Assignment Operators

A Java program to demonstrate the usage of assignment operators.

Problem Description

Write a Java program to demonstrate the usage of assignment operators (=, +=, -=, *=, /=, %=).

Code

AssignmentOperators.java
public class AssignmentOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 0;

        c = a + b;
        System.out.println("c = a + b = " + c);

        c += a; // c = c + a
        System.out.println("c += a = " + c);

        c -= a; // c = c - a
        System.out.println("c -= a = " + c);

        c *= a; // c = c * a
        System.out.println("c *= a = " + c);

        a = 10;
        c = 15;
        c /= a; // c = c / a
        System.out.println("c /= a = " + c);

        a = 10;
        c = 15;
        c %= a; // c = c % a
        System.out.println("c %= a = " + c);
    }
}

Output

c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a = 5

Explanation

  1. =: Simple assignment.
  2. +=: Add and assign.
  3. -=: Subtract and assign.
  4. *=: Multiply and assign.
  5. /=: Divide and assign.
  6. %=: Modulus and assign.

Try Yourself

  1. Compound Loop: Use += inside a loop to sum numbers from 1 to 10.
  2. Implicit Casting: Try byte b = 10; b += 5;. Does it work? Now try b = b + 5;. Why does one work and the other fail?
  3. String Append: Use += with a String variable to build a sentence word by word.
  4. Order of Operations: If a = 5, what is a *= 2 + 3? Is it (5 * 2) + 3 or 5 * (2 + 3)?
  5. Brain Twister: Can you use ^= to swap two integers without a temporary variable? (Recall the XOR swap).