Local Variable With Example In JAVA

A local variable is a variable declared inside a method body, block or constructor. It means variable is only accessible inside the method, block or constructor that declared it.

Important Note: 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.

Scope of Local Variable:

Scope of local variable are limited to method. Such a variable is accessible only within the method or block in which it is declared. The local variable’s scope starts from the line they are declared and their scope remains there until the closing curly brace of the method comes.

Declaration of Local Variable:

Every local variable declaration statement is contained by a block ({ … }). We can also declare the local variables in the header of a “for” statement. In this case it is executed in the same manner as if it were part of a local variable declaration statement.

For example: for(int i=0;i<=5;i++){……}

In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.


Syntax Of Local Variable:

methodname(){
<DataType> localvarName;
}

Here methodname is the name of method, DataType refers to data type of variable like int, float etc and localvarName is the name of local variable.

Example of Sytax of Local variable

int area()
    {
        int length=10; //local variable
        int breadth = 5; //local variable
        int rectarea = length*breadth; //local variable
        return rectarea;
        }

Program Example of Local Variable With Explanation:

Let us take an example in which we take local variable to explain it. Here, age is a local variable. This variable is defined under putAge() method and its scope is limited to this method only:

public class Dog

{

    public void putAge()

    {
        int age = 0; //local variable
        age = age + 6;
        System.out.println("Dog age is : " + age);
    }

    public static void main(String args[]){

        Dog d = new Dog();
        d.putAge();

    }

}

Output:

Dog age is : 6

Important Points To Remember:

  • Local variables are declared in a blocks, methods or constructors.
  • Local variables are created when the block, method or constructor is started and the variable will be destroyed once it exits the block, method or constructor.
  • Access modifiers cannot be used for declaring local variables.
  • Local variables are implemented at stack level internally.
  • Default values are not assigned to a local variables in Java.
  • Variables can also be define inside statement blocks i.e. do, for, while loop. These are only visible inside that block.

One thought on “Local Variable With Example In JAVA”