local variable in java

  • local variable will be created at time of method or block executed and destroy once the method or block execution complete.
  • This variable is declared inside method, block or constructor.
  • local variable is store inside stack memory.
  • JVM is not provide any default value for local variable. we should be initialize any value before using.
  • It is not necessary to perform initialization for local variable with in the logical blocks.
				
					public class LocalVariableTest {

	// constructor
	public LocalVariableTest() {
		int a = 10;
		System.out.println("inside constructor value :- " + a);
	}

	// inititalization block
	{
		int b = 34;
		System.out.println("inititalization bock value :- " + b);
	}

	// method
	public void hello() {
		int c = 67;
		System.out.println("inside method value :- " + c);
	}

	public static void main(String[] args) {

		LocalVariableTest t = new LocalVariableTest();
		t.hello();

		int d = 45;
		for (int i = 0; i < 3; i++) {
			d = d + i;
		}
		System.out.println("inside main method value :- " + d);
	}
}
				
			

Output :-
inititalization bock value :- 34
inside constructor value :- 10
inside method value :- 67
inside main method value :- 48