02: Variables – Giving Your Program a Memory
In our last tutorial, we printed text directly to the screen. But what if we want to store a username, a score in a game, or the price of an item? For that, we use Variables.
Think of a variable as a labeled box. You put data inside the box, give it a name, and then you can use that name later to get the data back.
🏗 The Rules of the Box
In Java, you can't just throw anything into a box. Java is Statically Typed, which means you must tell the computer exactly what kind of data the box will hold before you use it.
The 4 Most Common Data Types
| Type | What it holds | Example |
|---|---|---|
int |
Whole numbers (integers) | 10, -500, 2024 |
double |
Decimal numbers | 19.99, 3.14 |
String |
Text (must be in "quotes") | "c0der", "Java is fun" |
boolean |
Logic (True or False) | true, false |
💻 How to Declare a Variable
To create a variable, you follow this simple formula:
Type name = value;
public class Main {
public static void main(String[] args) {
// 1. Storing a name
String username = "YourName";
// 2. Storing an age
int age = 25;
// 3. Storing a grade
double gpa = 3.8;
// 4. Storing a status
boolean isDeveloper = true;
// Now, let's use them!
System.out.println("User: " + username);
System.out.println("Age: " + age);
}
}