CodeBlanks Logo Icon CodeBlanks

Assignment and increment

Learn =, +=, ++, -- assignment and increment operators.

Assignment and increment operators

= does assignment. Compound assignment operators like +=, -=, *=, /= combine the operation and the assignment.

int x = 10;
x += 5;  // x = x + 5  → 15
x -= 3;  // x = x - 3  → 12

++ and -- increment or decrement a variable by 1. They can come before (++x) or after (x++) the variable. Pre-increment increments then uses; post-increment uses then increments.

int x = 5;
int y = x++;  // y = 5, then x = 6
int z = ++x;  // x = 7, then z = 7

Practice Use compound assignment

Write a Main class with a main method. Assign 10 to int total. Do total += 5 and total++. Print total with println.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int total = 10;
        total += 5;
        total++;
        System.out.println(total);
    }
}

Expected output

16

Pre vs post increment

++x and x++ look the same but behave differently. ++x (pre-increment) increments then uses; x++ (post-increment) uses then increments.

int x = 5;
int a = ++x;  // x = 6, a = 6
int b = x++;  // b = 6, then x = 7

This distinction matters in loop counters and assignments. Standalone x++; or ++x; give the same result.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the assignment operators

Term Meaning
= Assignment
+= Add assign
++ Increment
-- Decrement

2 Complete the compound assignment

Question
int x = 10; x ____= 5;
Answer
int x = 10; x += 5;

Explanation: += combines addition with assignment.

3 What is the result of int x = 5; int y = x++;?

  • y = 6, x = 6
  • y = 6, x = 5
  • y = 5, x = 5
  • y = 5, x = 6 Correct answer

Explanation: x++ first assigns 5 to y, then makes x 6.

All lessons in Beginner