Three categories of Java variables have been explained thus far in these lessons.
The lifetime of a variable defines the portion of runtime during which the variable exists.
The type of the variable determines its initial state.
false
for boolean
, null
for objects). Scope refers to the area of a program in which an identifier is valid and has meaning.
private
and have class scope. Class scope begins at the opening left brace ({) of the class definition and terminates at the closing brace (}). Class scope enables methods to directly access all of its instance variables. An example of the scope of a variable is given in Code Sample 4-2. The class ScopeTest
is created with three methods:
Code Sample 4-2
The results show the following about the scope of the variable test:
main
, the value of test is 10, the value assigned within the main
method.printLocalTest
, the value of test is 20, the value assigned within the printLocalTest
methodprintClassTest
, the value of test
is 30, the private value assigned within ScopeTest
, because there is no value given to test
within the printClassTest
methodprintParamTest
, the value of test is 40, the value sent to the printParamTest
methodLast modified: December 12, 2022
Back to The Signature Of A Method