Variables & Robot Math 🔢
beginner25 XP

Robot Math (With Surprises!)

+, -, *, / and the mysterious % — with eggs, seeds and robots.

Robot Math (With Surprises!) 🧮

Java does math with +, -, * (times) and / (divide):

Java
public class Main {
    public static void main(String[] args) {
        int rows = 6;
        int seedsPerRow = 8;
        System.out.println("Seeds to plant: " + rows * seedsPerRow);
    }
}

😮 Surprise #1: whole-number division

When you divide two ints, Java throws away the decimal part:

Java
public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2);   // prints 3, not 3.5!
        System.out.println(7.0 / 2); // prints 3.5
    }
}

If you want decimals, use at least one double (like 7.0).

🥚 The remainder operator %

% gives the remainder: what's left over after dividing.

A farmer collects 17 eggs and packs them in cartons of 6:

Java
public class Main {
    public static void main(String[] args) {
        int eggs = 17;
        System.out.println("Full cartons: " + eggs / 6);
        System.out.println("Eggs left over: " + eggs % 6);
    }
}

That prints Full cartons: 2 and Eggs left over: 5. 🥚

💡

🧠 Trick: number % 2 is 0 for even numbers and 1 for odd numbers. Robots use this to do something every other time!

😮 Surprise #2: + with text and numbers

+ adds numbers, but glues text. Java works left to right:

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Total: " + 2 + 3);   // Total: 23
        System.out.println("Total: " + (2 + 3)); // Total: 5
    }
}

Brackets make Java do the math first.

🌱 Fun fact

Some farms use robots that plant seeds in perfectly straight rows and count every one, the same kind of math you just did!

☕

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/6
What does System.out.println(7 / 2); print?