Variables & Robot Math 🔢
beginner25 XP

Changing Values

Count points, drain batteries and level up with ++ and +=.

Changing Values 🔄

Variables can change. That's why they're called variables!

Java
public class Main {
    public static void main(String[] args) {
        int score = 0;
        score = score + 10;
        score = score + 5;
        System.out.println("Score: " + score);
    }
}

score = score + 10 means: take what's in score, add 10, put the answer back in score. Final score: 15.

Shortcuts programmers love ⚡

Long wayShortcutMeaning
score = score + 1;score++;add 1
score = score - 1;score--;take away 1
score = score + 5;score += 5;add 5
battery = battery - 10;battery -= 10;take away 10

🔋 A robot on a mission

Java
public class Main {
    public static void main(String[] args) {
        int battery = 100;
        battery -= 30; // drove across the field
        battery -= 25; // lifted a block
        battery += 40; // quick recharge
        System.out.println("Battery: " + battery + "%");
    }
}

Let's trace it like a detective 🕵️: 100 → 70 → 45 → 85. It prints Battery: 85%.

💡

💡 Tracing means following the code line by line and writing down each variable's value. It's the #1 skill for predicting what code does.

🌳 Fun fact

A tree grows a new ring every year. A tree-counting program could just do age++; once for every ring it sees!

☕

Want to run it yourself?

Predict what the code prints first, then check! Copy an example above, paste it into the free online Java editor, and press Run. Keep the first line as public class Main.

Open the online Java editor ↗

Opens Programiz, a free site that isn't run by First Coding Path and may show ads. Grown-ups, you might like to take a look first.

Quick check

01/5
int x = 5; x = x + 3; What is x now?