Local variables are declared inside a method and exist during its execution. Different methods can have the same name for a local variable. Still the variables have no relationship with each other.
In java default values are not assigned to local variables. Its contents are indeterminate until you explicitly assign a value to each local variables.
Note that local variables are only available within their scope. And scope of variable is the region of a program in which it may be directly accessed. In java a block i.e. "area between opening and closing curly brace" defines a scope. Each time you start a new block, you begin a new scope.
The most common scope for a local variable is that defined by a method. Local variables do not maintain their values from one method call to the next.
Note thatLocal variable may be declared with the same name as a static or instance variable, in this case the local variable hides the static or instance variable. Therefore, any reference to that name accesses the local variable.
Variables can also be define inside statement blocks i.e. do, for, while loop. These are only visible inside that block.
Syntax of Local Variable
type varName = value;
Example of Local Variable
Example 1 : Program that illustrates the local variables and it's scope
class Sample
{
static ctr = 0;
int i = 100;
void display1()
{
System.out.println("Before");
System.out.println("ctr = " + ctr);
System.out.println("i = " + i);
int ctr = 2, i = 200;
System.out.println("");
System.out.println("After");
System.out.println("ctr = " + ctr);
System.out.println("i = " + i);
}
void display2()
{
System.out.println("Another method");
System.out.println("ctr = " + ctr);
System.out.println("i = " + i);
}
}
class LocalVariables
{
public static void main(String args[])
{
Sample sObj = new Sample();
sObj.display1();
System.out.println("");
sObj.display2();
}
}
Output
Another method