Java ProgramsBasics & I/ODemonstrate Assignment Operators

Demonstrate Assignment Operators in Java

beginner·  Basics & I/O  ·  Operators

Problem

Compound assignment operators (+= -= *= /= %=) combine an arithmetic operation with an assignment in one step, updating a variable in place instead of writing it out as a separate operation and reassignment.

Starting from a single variable, apply each compound assignment operator in sequence and print the running value after each step.

Input
10
Output
Start: 10

Java Program

Java
public class DemonstrateAssignmentOperators { public static void main(String[] args) { int value = 10; // simple assignment System.out.println("Start: " + value); value += 5; // same as value = value + 5 System.out.println("After += 5: " + value); value -= 3; // same as value = value - 3 System.out.println("After -= 3: " + value); value *= 2; // same as value = value * 2 System.out.println("After *= 2: " + value); value /= 4; // same as value = value / 4 System.out.println("After /= 4: " + value); value %= 4; // same as value = value % 4 System.out.println("After %= 4: " + value); } }

Output

Start: 10 After += 5: 15 After -= 3: 12 After *= 2: 24 After /= 4: 6 After %= 4: 2

Core Logic

Each compound operator updates the same variable in place, so the running value from one step becomes the starting point for the next.

How It Works
  1. 1int value = 10; uses the plain = operator to assign the starting value.
  2. 2value += 5; is shorthand for value = value + 5;, updating value to 15.
  3. 3value -= 3;, value *= 2;, value /= 4;, and value %= 4; each apply the same shorthand pattern for subtraction, multiplication, division, and modulo.
  4. 4Because every step mutates the same variable, each operator's result depends on the value the previous operator left behind.
Starting from 10: += 5 gives 15, -= 3 gives 12, *= 2 gives 24, /= 4 gives 6, and %= 4 gives 2.
💡

Key Point: value += 5 isn't just shorter than value = value + 5 — for narrower types like byte or short, the compound form also does an implicit cast the long form would need written out explicitly.

Key Concepts

= operator+= operator-= operator*= operator/= operator%= operator

Related Programs