by Dinesh Thakur
  1. When the variable is declared within the method, block and constructor then the variable is treated as local variable.
  2. Local variable must be initialized before you call it otherwise it generates compile time error.
  3. Same local variable can be declared in two different blocks.
  4. Local variable never use any access specifier. It only takes the default access specifier.
  5. Local variable can never be declared through any access specifier except default access specifier.

Here is the java code for the program Local Variable in Java Example:

public class LocalVariableInJavaExample

{
          void show()
       {
            int LocVar = 10;
            System.out.println(LocVar); // local variable.
       }
         public LocalVariableInJavaExample()
      {
        int LocVar =15; // local variable within constructor.
        System.out.println(LocVar);
      }
         public static void main(String args[])
       {
         int LocVar = 5; // another local variable with same name
         LocalVariableInJavaExample l = new LocalVariableInJavaExample();
        l.show();
        System.out.println(LocVar);
       }
}

 

        Local Variable in Java Example