Variables
A variable is a named place to store a value so you can use it later: a price, a name, a count. In Java every variable has a type that decides what it can hold, and the compiler checks that you use it correctly.
Declaring and assigning
void main() { int age = 30; String name = "Ana"; double price = 19.99; boolean member = true; System.out.println(name + " is " + age); System.out.println("Price: " + price + ", member: " + member); }
Ana is 30 Price: 19.99, member: true
The form is type name = value;. int, double and boolean are primitive types (next lesson); String is a class for text.
Changing a value
void main() { int score = 10; System.out.println(score); score = 25; System.out.println(score); score = score + 5; System.out.println(score); }
10 25 30
After declaring a variable, assign new values without repeating the type. score = score + 5 reads the current value, adds 5 and stores the result.
Declare first, assign later
void main() { int total; total = 7 * 6; System.out.println(total); }
42
A local variable must be given a value before it's read; the compiler checks this:
void main() { int total; System.out.println(total); }
Main.java:3: error: variable total might not have been initialized
Types are fixed
void main() { int count = 5; count = "five"; }
Main.java:3: error: incompatible types: String cannot be converted to int
A variable's type can't change. This is what "statically typed" means, and it lets the compiler catch whole classes of bugs before the program runs.
Constants with final
void main() { final double TAX_RATE = 0.23; TAX_RATE = 0.2; }
Main.java:3: error: cannot assign a value to final variable TAX_RATE
final makes a variable unchangeable after it's assigned. Use it for values that shouldn't change; constants are conventionally named in UPPER_SNAKE_CASE.
Type inference with var
void main() { var city = "Lisbon"; // String var year = 2026; // int var ratio = 0.75; // double System.out.println(city + " " + year + " " + ratio); }
Lisbon 2026 0.75
With var (Java 10+), the compiler works out the type from the value. The variable is still statically typed — city is a String forever. Use var when the type is obvious from the right-hand side; spell it out when that helps readers.
Several variables at once
void main() { int x = 1, y = 2, z = 3; System.out.println(x + y + z); }
6
Allowed, but one declaration per line is usually clearer.
Try it yourself
Store a product name, a unit price and a quantity, then print the total cost.
4 x Notebook = 14.0