Variables
Learn how to declare, initialise, and name variables in Java - the containers that store data in your programs.
Overview
Key Points
- •Declaration: `int age;` - tells Java the type and name but does not set a value yet
- •Initialisation: `age = 25;` - assigns a value to a previously declared variable
- •Declaration + Initialisation: `int age = 25;` - the most common pattern
- •Variable names use camelCase: myAge, firstName, totalScore (start with lowercase)
- •Names cannot start with a digit, cannot contain spaces, and cannot be Java keywords (int, class, etc.)
- •Java is statically typed - a variable declared as int can only ever hold integers
Examples
Declaring and using variables
public class Main {
public static void main(String[] args) {
// Declare then initialise
int score;
score = 95;
// Declare and initialise on one line
String name = "Alice";
double height = 1.75;
boolean isStudent = true;
System.out.println(name + " scored " + score);
System.out.println("Height: " + height + "m");
System.out.println("Student: " + isStudent);
}
}String concatenation with + converts numbers and booleans to text automatically.
Updating a variable's value
public class Main {
public static void main(String[] args) {
int lives = 3;
System.out.println("Lives: " + lives); // 3
lives = lives - 1;
System.out.println("Lives: " + lives); // 2
lives = 0;
System.out.println("Lives: " + lives); // 0
}
}You can overwrite a variable's value at any time. The old value is gone.
Valid and invalid variable names
// Valid names
int age = 25;
String firstName = "Bob";
double averageScore = 88.5;
boolean isLoggedIn = false;
int _count = 0;
// Invalid names - these will NOT compile
// int 1stPlace = 1; ← cannot start with a digit
// String my name = ""; ← no spaces allowed
// int class = 5; ← 'class' is a reserved keyword
// double int = 3.14; ← 'int' is a reserved keywordJava reserved keywords (int, class, for, if, etc.) cannot be used as variable names.
Common Mistakes
- Using a variable before assigning it a value - Java will not compile: "variable might not have been initialized"
- Using PascalCase (MyAge) for variables - that convention is for class names; variables use camelCase (myAge)
- Trying to change a variable's type: declaring `int age = 25` then later writing `age = "twenty-five"` will not compile
Note
Java 10+ supports `var` for local variables: `var name = "Alice";`. The compiler infers the type from the right-hand side. Use it when the type is obvious to reduce verbosity.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4