🎉 Java Variables & Data Types — Explained Like You’re 5
🧠 What’s a Variable in Java?
Imagine a box with a label on it. You can put stuff in the box, change it later, or look inside when needed.
That’s a variable — it stores information for your program, like a name, number, or message.
Example:
String name = "Elly";
int age = 30;
🟨 String
= A type of variable (text)
🟦 int
= A type of variable (whole number)
🔍 Why Do We Use Variables?
Variables help you:
✅ Store info (like a score in a game)
✅ Use that info later
✅ Change it if needed
Without variables, you’d have to hard-code everything. That’s like writing a recipe without using ingredients!
📦 Types of Variables in Java (Data Types)
Let’s say we’re making a video game. Here are some “boxes” (variables) we might use:
Data Type | What It Stores | Example |
---|---|---|
int | Whole numbers | int lives = 3; |
double | Decimal numbers | double speed = 2.5; |
String | Text | String name = "Ali"; |
boolean | True or false (yes/no) | boolean gameOver = false; |
🛠 Java Variable Rules
Just like naming your pet, Java variables have rules:
❌ Can’t start with a number
✅ Must start with a letter or _
✅ Can’t use spaces or special symbols
✅ Case-sensitive (Score
≠ score
)
✅ Use clear names like playerName
, not x1
Good:
int score = 100;
String playerName = "Zara";
Bad:
int 3lives; // starts with number ❌
String name#1; // illegal character ❌
🧪 Let’s Write Some Code Together
Try this out in VS Code:
public class Main {
public static void main(String[] args) {
String name = "Rawisha";
int age = 25;
boolean isStudent = true;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Student? " + isStudent);
}
}
🔍 What it does:
➡ Prints out the variable values
➡ Shows how to combine text + variables
➡ Gives you a taste of how powerful this stuff is
🎮 Challenge Time!
Try these fun mini-challenges:
- Change the name to your own
- Add a
double
for your height - Add a
boolean
for “likesJava”
🧭 What’s Next? (Part 3 Preview)
Now you know what variables and data types are. Next up:
➡ How to make decisions in code
➡ What is an if
statement?
➡ How can your code do different things based on conditions?
Think of it like:
🟢 If you’re hungry → make a sandwich
🔴 If you’re tired → go to bed
We’ll turn your code into something that thinks!
🧩 Extra: Common Java Data Types Cheat Sheet
int age = 30; // Whole number
double price = 9.99; // Decimal number
char letter = 'A'; // Single character
String name = "Zara"; // Text
boolean isSunny = true; // true or false