Java Variables
Types of Variables
Java has three kinds of variables, each with a different scope and lifetime.
| Type | Declared In | Scope | Default Value |
|---|---|---|---|
| Local | Inside a method or block | Within that method/block only | None (must be initialized) |
| Instance | Inside a class, outside methods | Entire object | 0 / null / false |
| Static | Inside a class with static keyword | Entire class (shared by all objects) | 0 / null / false |
public class VariableTypes {
// Instance variable — belongs to each object
String name = "Java";
// Static variable — shared across all instances
static int instanceCount = 0;
public void display() {
// Local variable — exists only inside this method
int localVar = 10;
instanceCount++;
System.out.println("Name: " + name);
System.out.println("Local: " + localVar);
System.out.println("Count: " + instanceCount);
}
public static void main(String[] args) {
VariableTypes obj1 = new VariableTypes();
VariableTypes obj2 = new VariableTypes();
obj1.display();
obj2.display();
// instanceCount is now 2 — shared by both objects
}
}
Naming Conventions
Java follows well-established naming conventions to keep code readable and consistent.
Constants with final
Use the final keyword to declare a constant. Once assigned, its value cannot be changed.
public class Constants {
// Class-level constant (static final)
static final double PI = 3.141592653589793;
static final int MAX_USERS = 100;
public static void main(String[] args) {
// PI = 3.14; // ERROR: cannot assign a value to a final variable
// var keyword (Java 10+) — type is inferred by the compiler
var message = "Hello"; // inferred as String
var count = 42; // inferred as int
var price = 9.99; // inferred as double
System.out.println("PI = " + PI);
System.out.println("Max users = " + MAX_USERS);
System.out.println(message + " " + count + " " + price);
// var only works for local variables — not for fields or parameters
}
}
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.