Variables in Java – Types, Scope and Examples
A variable is a named place in memory that stores a value your program can read and change. In Java, every variable has a name, a type that decides what it can hold, and a scope that decides where it can be used.
This tutorial covers declaring and initialising variables, the three kinds of variables (local, instance and static), scope, final constants, and the naming rules every Java programmer follows.
1. What Is a Variable?
Think of a variable as a labelled box. The label is the name (price), the box's shape is the type (double), and what is inside is the value (49.5). You can look inside the box or replace its contents, but you cannot put a value of the wrong shape into it.
type name; // declaration
type name = value; // declaration with initialisation
int age = 30;
String city = "Pune";
boolean isMember = true;
2. Declaring, Initialising and Updating
public class VariableBasics {
public static void main(String[] args) {
int quantity; // declaration
quantity = 3; // initialisation (first assignment)
double price = 49.5; // declaration + initialisation
String item = "notebook";
double total = quantity * price;
System.out.println(quantity + " x " + item + " = " + total);
quantity = quantity + 2; // reassignment
quantity += 1; // shorthand for quantity = quantity + 1
System.out.println("New quantity: " + quantity);
int a = 1, b = 2, c = 3; // several variables of the same type
System.out.println("a + b + c = " + (a + b + c));
}
}
3 x notebook = 148.5 New quantity: 6 a + b + c = 6
- Declaration introduces the variable and its type.
- Initialisation gives it its first value. A local variable must be initialised before it is read, or the code will not compile.
- Assignment with
=replaces the current value; compound operators such as+=update it.
3. Kinds of Variables
| Kind | Declared | Exists | Copies | Default value |
|---|---|---|---|---|
| Local variable | Inside a method, constructor or block | While that code runs | One per call | None; must be assigned |
| Parameter | In a method or constructor signature | While the method runs | One per call | Set by the caller |
| Instance variable (field) | Inside a class, without static | As long as the object exists | One per object | Yes (0, false, null) |
| Static variable (class variable) | Inside a class, with static | As long as the class is loaded | One per class | Yes |
This example uses all of them. Changing the static school affects every student, while each student keeps its own name and marks:
public class VariableKinds {
static String school = "Green Valley"; // static (class) variable: one copy for the class
String name; // instance variable: one copy per object
int marks;
VariableKinds(String name, int marks) { // name and marks here are parameters
this.name = name;
this.marks = marks;
}
String result() {
String grade = marks >= 60 ? "Pass" : "Fail"; // local variable: lives only in this method
return name + " (" + school + "): " + grade;
}
public static void main(String[] args) {
VariableKinds s1 = new VariableKinds("Asha", 82);
VariableKinds s2 = new VariableKinds("Ravi", 45);
System.out.println(s1.result());
System.out.println(s2.result());
VariableKinds.school = "Blue Hills"; // changes it for every object
System.out.println(s1.result());
System.out.println(s2.result());
}
}
Asha (Green Valley): Pass Ravi (Green Valley): Fail Asha (Blue Hills): Pass Ravi (Blue Hills): Fail
4. Variable Scope
The scope of a variable is the part of the code where it can be used. In Java, a local variable is visible from its declaration to the end of the enclosing block { }.
public class ScopeDemo {
int count = 100; // field
void show(int count) { // parameter shadows the field
System.out.println("parameter count = " + count);
System.out.println("field count = " + this.count);
}
public static void main(String[] args) {
int total = 0; // visible in the whole main method
for (int i = 1; i <= 3; i++) { // i exists only inside the loop
int square = i * i; // square exists only inside one iteration
total += square;
}
// System.out.println(i); // compile error: cannot find symbol i
System.out.println("total = " + total);
{
int temp = 5; // block scope
System.out.println("temp = " + temp);
}
new ScopeDemo().show(7);
}
}
total = 14 temp = 5 parameter count = 7 field count = 100
- The loop variable
iandsquareexist only inside the loop. - A block
{ }creates its own scope. - A parameter or local variable with the same name as a field shadows the field; use
this.countto reach the field. - Two local variables in overlapping scopes cannot share a name.
5. Final Variables and Constants
A variable declared final can be assigned only once. For object references, final fixes the reference, not the object's contents. A static final field with a fixed value is a constant.
import java.util.ArrayList;
import java.util.List;
public class FinalVariables {
static final double GST_RATE = 0.18; // a constant: UPPER_SNAKE_CASE
public static void main(String[] args) {
final int maxUsers = 50;
// maxUsers = 60; // compile error: cannot assign a value to final variable
final List<String> names = new ArrayList<>();
names.add("Asha"); // allowed: the object can change
names.add("Ravi");
// names = new ArrayList<>(); // not allowed: the reference cannot change
System.out.println("Limit " + maxUsers + ", names " + names);
System.out.println("GST on 1000 = " + 1000 * GST_RATE);
}
}
Limit 50, names [Asha, Ravi] GST on 1000 = 180.0
Learn more in final keyword in Java.
6. Naming Rules and Conventions
Rules (enforced by the compiler)
- Names can contain letters, digits,
_and$. - They must not start with a digit.
- They must not be a reserved keyword such as
class,intornew. - They are case-sensitive:
totalandTotalare different variables. - A single underscore
_on its own is not a valid name; since Java 22 it marks an unnamed variable.
Conventions (followed by everyone)
| What | Style | Examples |
|---|---|---|
| Variables and parameters | camelCase | firstName, totalAmount, isActive |
| Constants | UPPER_SNAKE_CASE | MAX_SIZE, GST_RATE |
| Booleans | Read as yes/no questions | isValid, hasMore, canEdit |
Choose descriptive names (orderCount) over short ones (oc), except for tiny scopes such as loop counters (i).
7. Using var for Local Variables
Since Java 10, you can write var instead of the type for local variables that have an initial value. The compiler infers the type:
var count = 10; // int
var message = "Hello"; // String
var prices = new ArrayList<Double>(); // ArrayList<Double>
// var x; // error: cannot infer type without an initializer
// var y = null; // error: cannot infer type from null
Use var when the type is obvious from the right-hand side; write the type explicitly when it helps readers.
8. Where Variables Live in Memory
- Local variables and parameters live in the method's stack frame and disappear when the method returns.
- Instance variables live inside their object on the heap.
- Static variables are stored with the class data and live as long as the class is loaded.
For reference types, the variable stores a reference; the object itself is always on the heap.
9. Common Mistakes
- Using a local variable before assigning it:
variable might not have been initialized. - Using a variable outside its block:
cannot find symbol. - Accidentally shadowing a field with a parameter and forgetting
this.in a constructor. - Making a variable
staticwhen each object needs its own value. - Assuming
finalmakes an object immutable.
10. Summary
- A variable has a type, a name, a value and a scope.
- Local variables live inside methods and must be initialised; fields get default values.
- Instance variables belong to each object; static variables are shared by the class.
finalvariables can be assigned once;static finalvalues are constants.- Follow camelCase for variables and UPPER_SNAKE_CASE for constants.
Related Tutorials
Reference: dev.java: Variables
Frequently Asked Questions (FAQ)
Q1. What is a variable in Java?
A variable is a named storage location with a fixed type. It holds a value that your program can read and, unless it is final, change.
Q2. What are the types of variables in Java?
Local variables (inside methods or blocks), instance variables (non-static fields, one per object) and static variables (one per class). Method parameters behave like local variables.
Q3. What is the difference between a local and an instance variable?
A local variable is declared inside a method, exists only while it runs and has no default value. An instance variable is declared in the class body, exists as long as the object does, and gets a default value.
Q4. What is a static variable?
A field declared with static. It belongs to the class, not to any object, so all objects share the same copy. It can be accessed with the class name, such as Counter.total.
Q5. Do local variables have default values?
No. The compiler requires every local variable to be definitely assigned before it is read. Fields, by contrast, are automatically set to 0, false or null.
Q6. What is variable scope?
The region of code where a variable can be used. Local variables are visible from their declaration to the end of their block; fields are visible throughout the class (and beyond, depending on access modifiers).
Q7. What is variable shadowing?
When a local variable or parameter has the same name as a field, it hides the field inside that scope. Use this.name to refer to the field, as is common in constructors.
Q8. What is a final variable?
A variable that can be assigned only once. For primitives, the value cannot change; for references, the variable always points to the same object, though the object itself may still be mutable.
Q9. How do I declare a constant in Java?
Use static final and an uppercase name: public static final int MAX_USERS = 100;. Java has a const keyword, but it is reserved and unused.
Q10. Can a variable name start with a number?
No. Names may contain digits but cannot start with one. item1 is valid; 1item is not.
Q11. Are Java variable names case-sensitive?
Yes. count, Count and COUNT are three different names.
Q12. Can I declare multiple variables in one line?
Yes, if they have the same type: int a = 1, b = 2, c;. For readability, one declaration per line is usually preferred.
Q13. What is the var keyword?
Introduced in Java 10, var lets the compiler infer the type of a local variable from its initializer. It cannot be used for fields, method parameters or return types.
Q14. Where are variables stored in memory?
Local variables and parameters are stored in stack frames. Instance variables are stored inside objects on the heap. Static variables are stored with the class's runtime data.
Q15. Can I use a variable declared inside a loop after the loop?
No. Its scope ends at the loop's closing brace. Declare it before the loop if you need it afterwards.
Q16. What is the difference between a variable and a constant?
A variable's value can change; a constant's value is fixed. In Java, a constant is usually a static final field initialised with a value known at compile time.
Q17. Can a static method use instance variables?
Not directly, because a static method has no current object. It must first get an object reference and access the field through it.
Q18. What happens to a local variable after a method returns?
Its stack frame is removed and the variable no longer exists. If it referred to an object that nothing else references, that object becomes eligible for garbage collection.
Q19. What are the naming conventions for Java variables?
Use camelCase for variables and parameters (totalPrice), UPPER_SNAKE_CASE for constants (MAX_RETRIES), and meaningful names that describe the value.
Q20. What is an unnamed variable in Java?
Since Java 22, a single underscore can be used for a variable you must declare but never use, for example in catch (Exception _) or a lambda parameter (_, value) -> .... It makes the intent clear.