Introduction
A running program need to store and refer to values. "A variable is a storage location [...]" (JLS3), that can hold a value.
A variable has a name, so that it is possible to refer to it. A variable has a type, so that it is certain what type of value it contains, and what operators that may be used with the variable. Finally, a variable has a value that it stores, which is the reason why variables are necessary in programs in the first place.
Local Variables
A local variable is a variable inside a method block. All local variables must be declared and initialized before they are used.
public class Main { public static void main(String[] args) { int theAnswer; // declaration theAnswer = 42; // initialization } }
Here, the type is int
,
the variable is theAnswer
,
the operator is =
and
the value is 42
.
The variable is declared and initialized in two steps.
public class Main { public static void main(String[] args) { int theAnswer = 42; // declaration and initialization } }
The variable is declared and initialized in one single step.
This is a somewhat simplified grammar rule for the declaration:
- LocalVariableDeclaration =
- Type, Identifier, '=', Literal ';' ;
Concept: Every variable has a type.