Declaring a Variable
Purpose:
- To provide space in memory to describe an instance's state or as a temporary storage place.
Mechanics:
<modifiers> <datatype> <variable name>;or<modifiers> <datatype> <variable name> = <expression>;
Example:
private int number;orprivate int number = 0;
Usage:
- <modifiers> is an optional space-separated list of valid modifiers.
- <datatype>, either the name of a class or a base type, declares to which class the variable will refer or which base type the variable will be.
- <variable name> is any valid identifier which is unique to the current scope.
- <expression> is an optional variable, function, or parameter - or any combination of them, with operators and parentheses - that evaluates to the same type as <datatype> and whose value the variable should assume immediately upon creation. If <expression> has multiple parts, as in a chain of arithmetic operations, then it is evaluated according to the heirarchy of operations.
- An instance variable describes the state of an instance. It is declared within the scope of a class.
- A local variable is a temporary storage place of information. It is declared within the scope of an individual method.
Restrictions:
- Only an instance variable can be declared with a list of modifiers. If an instance variable is given an initial value, that value is stored in the variable before the first statement of the constructor of the object is executed.
email suggestions to: cs015tas@cs.brown.edu
