Variables Need Types
int, double, String and boolean: labels for your robot's memory.
Variables Need Types 📦
A variable is a labeled box that stores a value. Java is extra careful: every box also says what kind of thing goes inside. That's its type.
public class Main {
public static void main(String[] args) {
String robotName = "RoverBot";
int battery = 87;
double speed = 1.5;
boolean isCharging = false;
System.out.println(robotName + " battery: " + battery + "%");
System.out.println("Charging? " + isCharging);
}
}| Type | Holds | Example |
|---|---|---|
int | whole numbers | int moons = 2; |
double | numbers with a decimal point | double temp = 21.5; |
String | text (capital S!) | String planet = "Mars"; |
boolean | only true or false | boolean raining = true; |
The pattern is always: type name = value;
Why types? 🤔
Types stop silly mistakes. If you try to put text into a number box, Java refuses before your robot ever moves:
int battery = "full"; // ❌ text can't go in an int boxThat's a good thing! It's much better to find the bug at your desk than in the middle of a robot competition.
Naming boxes
Java programmers use camelCase: start lowercase, then a capital for each new word: batteryLevel, isCharging, tallestMountain.
🌡️ Fun fact
Weather stations measure temperature as decimals, like 21.5 degrees, so a program storing them would use double. The number of days in a week? Always whole, so int is perfect.
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.
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.