Java Variables: Declaration, Scope, Fields and Constants
A variable associates a name and type with a value that a program can read or change.
Declaration and initialization
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:
| |
Local variables
Variables declared inside a method, constructor, or block are local to that scope:
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:
Java passes arguments by value. For an object, the copied value is the object reference.
Instance fields
An instance field belongs to each object:
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:
Constants
final prevents reassignment. Constants are commonly static final and use upper snake case:
| |
For ordinary names, use descriptive lower camel case such as currentScore. Avoid Java keywords, leading digits, and names that differ only by capitalization.