The Concept: The "Labeled Box"
Imagine you are moving into a new house. You have a bunch of boxes. To keep things organized, you put a label on each box: "Books," "Kitchenware," or "Clothes." You wouldn’t put a soup ladle in the "Books" box, right?
In Java, Variables are those boxes. They are containers in the computer's memory that hold data. Because Java is a Statically Typed language, you must tell the computer exactly what kind of data is going into that box before you use it. You can't change the box's type later.
The Two Categories of Data Types
1. Primitive Types (The Basics)
These are built into the language and are very fast. There are 8, but these 4 are the ones you'll use 90% of the time:
int: For whole numbers (e.g., 10, -500, 42).double: For decimal numbers (e.g., 3.14, 19.99).boolean: For true/false values (like a light switch).char: For a single character (e.g., 'A', '$').
2. Non-Primitive (Reference) Types
These are more complex. The most common one is:
String: For sequences of characters (e.g., "Hello World"). Notice it starts with a capital 'S'—that's a hint that it's a Class, not just a simple primitive!
How to Declare a Variable
The syntax follows this pattern: type variableName = value;
type: What kind of data?variableName: What is the "label" on the box? (Use "camelCase" likemyAge).=: The assignment operator (it puts the value into the box).;: The semicolon (every Java "sentence" must end with one).
The Code Example
public class VariablesDemo {
public static void main(String[] args) {
// 1. Integer (Whole number)
int score = 100;
// 2. Double (Decimal number)
double price = 19.99;
// 3. String (Text - must be in double quotes)
String playerName = "Alex";
// 4. Boolean (True or False)
boolean isGameOver = false;
// 5. Char (Single character - must be in single quotes)
char grade = 'A';
// Printing them out to see the values
System.out.println("Player Name: " + playerName);
System.out.println("Current Score: " + score);
System.out.println("Item Price: $" + price);
System.out.println("Final Grade: " + grade);
System.out.println("Is the game over? " + isGameOver);
// We can also change (update) a variable's value
score = score + 50;
System.out.println("Updated Score: " + score);
}
}Expected Output
Player Name: Alex
Current Score: 100
Item Price: $19.99
Final Grade: A
Is the game over? false
Updated Score: 150Without variables, programs would be "static"—they would do the same thing every time. Variables allow your program to have a memory. It allows you to track a user's name, calculate a total in a shopping cart, or remember if a user is logged in.