A variable associates a name and type with a value that a program can read or change.
Declaration and initialization
1 | int age; |
Java is statically typed, so the declared type determines which values and operations are allowed. var can infer a local variable’s compile-time type from its initializer:
1 | var message = "Hello"; // Inferred as String |
Local variables
Variables declared inside a method, constructor, or block are local to that scope:
1 | void printTotal(int quantity) { |
Local variables must be definitely assigned before use. Their lifetime ends when execution leaves the relevant scope.
Parameters
Method and constructor parameters receive values from the caller and behave like initialized local variables:
1 | int add(int left, int right) { |
Java passes arguments by value. For an object, the copied value is the object reference.
Instance fields
An instance field belongs to each object:
1 | class Player { |
Every Player has its own name and score. Fields receive default values if no initializer is supplied.
Static fields
A static field belongs to the class and is shared by all instances:
1 | class Player { |
Constants
final prevents reassignment. Constants are commonly static final and use upper snake case:
1 | private static final int MAX_RETRIES = 3; |
For ordinary names, use descriptive lower camel case such as currentScore. Avoid Java keywords, leading digits, and names that differ only by capitalization.