Variables in Java
Introduction
In this chapter, you will learn what variables are and how to declare and use them in Java. Variables are among the most important building blocks in programming because they let you store and reuse data. If the idea feels abstract at first, we use simple metaphors—and you will deepen numeric types in Numbers.
Prerequisites
- JDK 21 and an editor set up
- Completed Coding Standards (naming will matter here)
- Ability to run a small
mainclass in IntelliJ or the terminal
What Is a Variable
A variable is a named storage location with a type. In Java, you must declare the type before (or when) you use the name.
Think of it like:
- A labeled box with a size label: the label is the variable name (
userName), the size label is the type (String), and the content is the value ("Alice"). - A parking slot sign: the sign says what kind of vehicle may park there—Java will not let you park a
Stringin anintslot.
public class VariableDemo {
public static void main(String[] args) {
String userName = "Alice";
System.out.println(userName);
}
}Why Variables Matter
Without variables, you would repeat literal values everywhere, which makes code hard to change and easy to break.
With variables, you can:
- Reuse values
- Update values in one place
- Make code easier to read
- Build logic step by step
Tip
Memory Trick
Variable = type + name + value.
In Java, the type is part of the contract—it is checked at compile time.
Declaration and Assignment
Java uses an explicit type and = for assignment.
// Declare and initialize in one line
int age = 18;
String city = "New York";
double price = 9.99;
boolean isStudent = true;
char grade = 'A';You can also declare first, then assign:
int score;
score = 95;Unlike Python, you cannot write age = 18 without a type in normal local variable code—the compiler needs to know what age holds.
Use Variables in Expressions
Variables are most useful when combined.
public class NotebookTotal {
public static void main(String[] args) {
double notebookPrice = 12.5;
int quantity = 3;
double totalCost = notebookPrice * quantity;
System.out.println(totalCost);
}
}Variables Can Change (With the Same Type)
You may assign a new value to the same variable name if the new value matches the declared type.
int score = 60;
score = score + 10;
System.out.println(score); // 70Metaphor: same box label, new content—as long as the content still fits the type (int).
int count = 1;
// count = "two"; // Compile error: String cannot be assigned to intJava is statically typed: each variable has a fixed type at compile time. This differs from Python, where a name can later refer to a different type.
Primitive Types vs Reference Types (Overview)
Java has two broad categories:
| Category | Examples | Beginner mental model |
|---|---|---|
| Primitive | int, double, boolean, char, … | Stores the value directly |
| Reference | String, arrays, objects you define | Stores a reference to data elsewhere |
This chapter uses common types only. Full numeric ranges (byte, short, long, float) and wrapper classes are covered in Numbers. Object-oriented details come in later OOP chapters.
For now, remember:
int,double,boolean,charare primitivesStringis a reference type (but easy to use like text)
Naming Rules and Best Practices
Follow Java rules and Coding Standards:
Legal rules
- Names may contain letters, digits,
_, and$(avoid$in your own code) - Must not start with a digit
- Names are case-sensitive (
ageandAgeare different) - Cannot use keywords such as
class,if,for(see Keywords)
Style
- Use meaningful camelCase names:
userName,totalPrice,retryCount
Good:
int retryCount = 0;
String userName = "Lee";Avoid:
int x = 0;
String s = "Lee";final Variables (Constants in a Method)
When a variable should not be reassigned, use final:
final int MAX_ATTEMPTS = 3;
final String APP_NAME = "HelloCode";
// MAX_ATTEMPTS = 5; // Compile errorFor class-level constants, combine static final and UPPER_SNAKE_CASE (see coding standards).
Common Beginner Mistakes
Mistake 1: Using a Variable Before Declaring It
public class Broken {
public static void main(String[] args) {
System.out.println(userAge); // Cannot find symbol
}
}Fix:
int userAge = 20;
System.out.println(userAge);Mistake 2: Type Mismatch
int age = "18"; // Incompatible typesFix: use the correct literal or convert intentionally (conversion details appear in later chapters):
int age = 18;Mistake 3: Forgetting That Java Is Not Python
# Python — dynamic
x = 10
x = "ten"// Java — same variable must stay int
int x = 10;
// x = "ten"; // ErrorMini Practice
Try this in your IDE:
public class LearningProgress {
public static void main(String[] args) {
String name = "Tom";
int learningDays = 9;
String message = name + " has studied Java for " + learningDays + " days.";
System.out.println(message);
}
}Expected output:
Tom has studied Java for 9 days.What’s Next
Learn how to document intent with Comments, then Operators for calculations and comparisons.
FAQ
Do variables store data directly?
Primitives store values directly in the variable. Reference types store a reference to an object; the object lives elsewhere in memory. At beginner level, String name = "Tom" behaves like “name holds text.”
Why does = not mean mathematical equality?
In Java, = is assignment. Equality testing uses == for primitives and .equals() for many objects (especially String)—covered when you study operators and strings.
Can one variable change from int to String?
No. Once int age is declared, only int values (within range) may be assigned to age.
How do I choose better variable names?
Describe purpose, not implementation noise. If a reader can guess meaning from the name, it is usually good.
Do I need to memorize every numeric type now?
No. Use int for whole numbers and double for decimals in exercises until Numbers.