Explain it simply
Variables in plain words
A variable is a named box for keeping a piece of data. You can put `30` into a box called `age` and later replace it with `31`.
What makes Java different is that every box carries a label (a type) saying what may go inside. Java asks up front, 'what kind of thing are we putting in this box?'. If you try to put text into a box labelled `int`, the compiler stops you before the program ever runs.
Problem → Why → Solution
The problem: the wrong thing in a box, or opening an empty box
Say you are writing code that reads an age from a form and stores it in a variable. Forms always hand you text, so you put `"30"` straight into an `int`. Then you declare `total` but try to print it before giving it a value.
In some languages code like this runs and quietly prints `undefined` or some wrong value. Java rejects both lines at compile time.
public class Main {
public static void main(String[] args) {
int age = "30"; // error: incompatible types:
// String cannot be converted to int
int total;
System.out.println(total); // error: variable total might not
// have been initialized
}
}Why Java is this strict
Once a variable's type is declared, it never changes for the rest of the program (static typing). So the compiler knows exactly what values each variable may hold and can catch mismatches early. Refusing to read a local variable that has no value yet also removes a whole class of bugs caused by leftover 'garbage' values.
Core concept: type, value and scope
There are three things you do with a variable. A declaration (`int age;`) states its type and name. An initialization (`int age = 30;`) gives it a first value at the moment it is declared. An assignment (`age = 31;`) puts a new value into an existing variable, replacing the old one. You do not repeat the type in an assignment; if you do, it counts as declaring a new variable and you get an 'already defined' error.
Local variables, the ones declared inside a method, have no default value. The compiler checks every code path and only accepts a read if the variable has definitely been given a value before that point (it is 'definitely assigned').
Every variable also has a scope: it is visible only inside the `{ }` block that declares it, and its name disappears when that block closes. Using a variable declared inside a block from outside it gives 'cannot find symbol'.
| Keyword | What it does | Watch out |
|---|---|---|
| `final` | Can be assigned only once | Reassigning is a compile error |
| `var` | Compiler infers the type from the initializer | The type is fixed, not dynamic |
`var` was added in Java 10 and works only for local variables. With `var city = "Yangon";` the compiler decides that `city` is a `String`, and rejects any later attempt to store a number in it. Without an initializer there is nothing to infer from, so `var x;` is a compile error. Name variables in camelCase like `totalScore`, using only letters, digits, `_` and `$`; a name cannot start with a digit or be a keyword such as `class`.
- Declare a type and a name
- Store a first value
- Reassign as often as needed
- Block closes, the name is gone
`final` removes step three, and `var` lets the compiler choose the type in step one; either way the type stays fixed.
General pattern: variables
Type name = value; // declare + initialize
name = newValue; // reassign (same type, no type keyword)
Type later; // declare now...
later = value; // ...assign before the first read
final Type fixed = value; // can never be reassigned
var inferred = value; // type inferred at compile time (locals only)The type appears only on the line that declares the variable. Reassigning needs just the name and the value. `final` and `var` are optional keywords that go in front of a declaration.
Storing a profile in variables
The program below stores a person's profile in four variables of different types, reassigns `age`, and also shows `final` and `var`. Before running it, predict whether the `Age:` line shows 30 or 31. Afterwards, add the line `maxAge = 130;` and see for yourself what the compiler says.
public class Main {
public static void main(String[] args) {
String name = "Aung";
int age = 30;
double height = 5.8;
boolean isStudent = false;
age = age + 1; // reassign: the old value is replaced
final int maxAge = 120; // final: can never be reassigned
var city = "Yangon"; // var: the compiler infers String
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Student: " + isStudent);
System.out.println("City: " + city + ", max age " + maxAge);
}
}Code breakdown
- Declare and initialize
int age = 30;Declares `age` with type `int` and stores `30` right away. From now on `age` can only ever hold whole numbers.
- Reassign using the old value
age = age + 1; // reassign: the old value is replacedThe right side runs first: it reads the current value `30`, adds `1` to get `31`, and then stores `31` back into `age`. Notice that the type is not repeated.
- A constant
final int maxAge = 120; // final: can never be reassignedBecause of `final`, writing `maxAge = 130;` later would fail with 'cannot assign a value to final variable maxAge'.
- Type inference with var
var city = "Yangon"; // var: the compiler infers String`"Yangon"` is a String, so `city` gets type `String`. It is exactly the same as writing `String city = "Yangon";`; the type cannot change at run time.
- Joining values into text
System.out.println("City: " + city + ", max age " + maxAge);When `+` involves a String, the other values are turned into text and joined, so `120` becomes part of the text too.
Name: Aung
Age: 31
Height: 5.8
Student: false
City: Yangon, max age 120Scope: how far a variable can be seen
A variable declared in a block is visible in that block and in any block nested inside it. Variables from an outer block can be used from inside. So declare each variable in the smallest block that still covers every place you use it.
Nested scopes
-------------
main() { <- total lives here
int total = 0;
if (...) { <- bonus lives only in here
int bonus = 5;
total = total + bonus; OK: total is visible inside
}
print(bonus); <- ERROR: cannot find symbol bonus
}In real projects
In real applications
All app data, from user profiles, product prices and login status to game scores and stock counts, starts with this variable concept. In production code, developers choose names that are longer but clear: `remainingStock` instead of `x`, `isEmailVerified` instead of `flag`. Whoever reads the code six months later, often yourself, should understand a value from its name alone.
Many teams follow the rule 'if it does not change, make it `final`'. In a long method, knowing that a value never changes makes the code easier to follow, and the compiler catches any accidental reassignment. `var` is used where the type is obvious from the right-hand side, as in `var orders = new ArrayList<Order>();`, and avoided where it hides the type, as in `var x = getData();`.
Common mistakes
Common variable mistakes
Repeating the type when reassigning
After `int score = 5;`, writing `int score = 6;` tells Java you are declaring a second variable with the same name, and it refuses with 'variable score is already defined'. To change an existing variable, write just `score = 6;`.
Thinking `var` makes a variable dynamic
People coming from JavaScript often try `var count = 10;` followed by `count = "ten";`. `count` became an `int` at compile time, so they get 'incompatible types: String cannot be converted to int'. `var` saves typing; it does not relax the type rules.
Using a block's variable outside it
Declare a variable inside an `if` and try to print it after the `if`, and you get 'cannot find symbol'. Declare it before the block and assign it inside.
Best practices
Naming variables well
The compiler accepts any name that follows the rules, but a name people can read is a separate matter. A variable's name should reveal what it stands for. Give boolean variables question-like names such as `isActive` or `hasPaid`, so an `if` reads like a sentence. Declare variables close to where they are used, and do not reuse one variable for two different jobs.
| Name | Allowed? | Why |
|---|---|---|
| `totalPrice` | Yes, ideal | camelCase and clear meaning |
| `2ndPlace` | No | Cannot start with a digit |
| `class` | No | It is a keyword |
| `tp` | Yes, but poor | Nobody can tell what it means |
Mini challenge
Mini challenge: a score board with a swap
Store two players' names and scores in variables. Add a `final` bonus to the first player, then use temporary variables to swap the names and scores so the higher score comes first.
- Use `final int bonus = 30;`
- Mya starts at 90 and must reach 120 after the bonus; Ko Ko has 140
- Use two temporary variables for the swap (one for the name, one for the score)
- Print `1st: Ko Ko (140)` and `2nd: Mya (120)`
public class ScoreBoard {
public static void main(String[] args) {
// TODO: a final int bonus of 30
// TODO: String first = "Mya", String second = "Ko Ko"
// TODO: int firstScore = 90, int secondScore = 140
// TODO: add the bonus to firstScore (reassign, do not redeclare)
// TODO: swap first/second and firstScore/secondScore with temp variables
// TODO: print "1st: <name> (<score>)" and "2nd: <name> (<score>)"
}
}Expected: Two lines: `1st: Ko Ko (140)` and `2nd: Mya (120)`.
Show hint
A swap takes three steps, like `String tempName = first; first = second; second = tempName;`. Without the temp variable, one value would be lost.
Show solution
public class ScoreBoard {
public static void main(String[] args) {
final int bonus = 30;
String first = "Mya";
String second = "Ko Ko";
int firstScore = 90;
int secondScore = 140;
firstScore = firstScore + bonus;
String tempName = first;
first = second;
second = tempName;
int tempScore = firstScore;
firstScore = secondScore;
secondScore = tempScore;
System.out.println("1st: " + first + " (" + firstScore + ")");
System.out.println("2nd: " + second + " (" + secondScore + ")");
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Declare with `Type name = value;` and reassign with `name = newValue;`
- A local variable can be read only after it has a value (definite assignment)
- `final` forbids reassignment; `var` infers the type at compile time
- A variable exists only inside the `{ }` block that declares it