- When the variable is declared within the method, block and constructor then the variable is treated as local variable.
- Local variable must be initialized before you call it otherwise it generates compile time error.
- Same local variable can be declared in two different blocks.
- Local variable never use any access specifier. It only takes the default access specifier.
- 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); } }