Information Technology Reference
In-Depth Information
Local Variables
Like fields, local variables store data. While fields usually store data about the state of the
object, local variables are usually created to store data for local, or transitory, computations.
Table 5-1 compares and contrasts local variables and instance fields.
The following line of code shows the syntax of local variable declarations. The optional ini-
tializer consists of the equals sign followed by a value to be used to initialize the variable.
Variable name
Type Identifier = Value ;
Optional initializer
￿
The existence of a local variable is limited to the block in which it is created.
-
It comes into existence at the point at which it is declared.
-
It goes out of existence when the block completes execution.
￿
You can declare local variables at any position in the method body.
The following example shows the declaration and use of three local variables of type int .
static void Main( )
{
int FirstInt = 15;
int SecondInt = 13;
int Total = FirstInt + SecondInt;
...
}
Table 5-1. Instance Fields vs. Local Variables
Instance Field
Local Variable
Lifetime
Starts when the instance is created.
Ends when the instance is no longer
accessible.
Starts at the point in the block where it
is declared.
Ends when the block completes
execution.
Implicit
Initialization
Initialized to a default value for
the type.
No implicit initialization. The value
remains undefined until it is assigned to.
Storage Area
All the fields of a class are stored in the
heap, regardless of whether they are
value types or reference types.
Value type: stored on the stack.
Reference type: reference stored on
the stack, and data stored in the heap.
Search WWH ::




Custom Search