Java Variables
Java variables are named containers that store values your program works with. Every variable in Java has a type, which decides what kind of value it can hold, and that type cannot change later.
Declaring Variables
The pattern is type name = value;. You can also declare first and assign later.
public class Main {
public static void main(String[] args) {
String name = "Ayesha";
int age = 27;
double height = 1.65;
boolean student = false;
int score; // declared
score = 88; // assigned later
System.out.println(name + " is " + age + " years old.");
System.out.println("Height: " + height + ", student: " + student);
System.out.println("Score: " + score);
}
}Ayesha is 27 years old. Height: 1.65, student: false Score: 88
Changing a Variable
A normal variable can be given a new value of the same type at any time.
public class Main {
public static void main(String[] args) {
int level = 1;
level = 2;
level = level + 1;
System.out.println("Level " + level);
}
}Level 3
Type Inference with var
Since Java 10 you can write var for local variables and the compiler figures out the type from the value. The variable is still strongly typed: once var count = 5 is an int, it stays an int.
public class Main {
public static void main(String[] args) {
var city = "Lahore"; // String
var population = 13_000_000; // int (underscores improve readability)
var ratio = 0.75; // double
System.out.println(city + ": " + population + " people, ratio " + ratio);
}
}Lahore: 13000000 people, ratio 0.75
Constants with final
Mark a variable final when its value should never change. Trying to reassign it is a compile error.
public class Main {
public static void main(String[] args) {
final double TAX_RATE = 0.17;
double price = 200;
System.out.println("Tax: " + price * TAX_RATE);
// TAX_RATE = 0.2; // error: cannot assign a value to final variable
}
}Tax: 34.0
Java Variable Naming Rules
- Names may contain letters, digits, underscores and dollar signs.
- A name cannot start with a digit.
- Names are case sensitive: total and Total are different variables.
- Reserved words such as int, class or new cannot be used as names.
- By convention use camelCase and descriptive names like orderTotal, not x.
Frequently asked questions
Should I use var in Java?
Use var when the type is obvious from the right-hand side, such as var list = new ArrayList<String>(). Write the type explicitly when it makes the code clearer.
Can I declare multiple variables in one line in Java?
Yes, if they share a type: int x = 1, y = 2, z = 3;. For readability, most style guides prefer one declaration per line.
What happens if I use a local variable before assigning it?
The compiler reports "variable might not have been initialized". Local variables have no default value, unlike fields in a class.