Scope of Variables
Scope of Variables
Java variables are classified into three kinds :
- Instance variables
- Class variables
- Local variables
Instance and class variables are declared inside a class, instance variables are created when the objects are intantiated and therefore are associated with the objects. They take different values for each object. Class variables are global to a class and belongs to the entire set of objects that the class creates. Only one memory location is creates for each class variables.
Variables decleared inside the methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside the program bloacks that are defined within an opening brackets ( { ) and closing brackets ( } ). These variables are vissible to the program only from the begining of its program bloack to the end of the program bloack. When the program control leaves a block all the variables in the block will cease to exist. The area of the program where variable is accessible i.e. usable is its scope.
For example :
{
Int x = 0;
{
:
:
Int n = 5;
:
:
}
{
:
:
Int m = 10;
:
:
}
}
Each block can contain its own set of local variable declarations. We cannot declare a variable to have the same name as one in an outer bloack. . the variables x declared in one block is available in all the three bloacks, how ever the variables declared in Block 2 is available only in Block 2, because it goes out of the scope at the end of the block 2, Similarly m is accessible only in block 3.
Note : We cannot declare the variable x again in block 2 and Block 3 ( This is perfectly legal in C and C Plus Plus. ).
Type Casting :
The process of converting one data type to another is called casting.
For example :
Int m = 50;
Byte n = (byte)m;
Long count = ( long )m;
Casting is required when a method returns a type different than the one we require.
Four integer types can be cast to any other type except Boolean. Casting into smaller type may result in loss of data. Similarly the float and double can be cast to any other type except Boolean.