What is local variable in java with example

A local variable in java: – Local variable a created inside the method and should be used only within the created method. if used the outside created method then it will give us errors shown in the below program.

Local variable in java Program

public class A  {
	public static void main(String[] args) {
		int x=10;
	}
	public void test() {
		System.out.println(x);  // Error
	}
}

Example 2

public class A  {
	public static void main(String[] args) {
		int x=10;
		System.out.println(x); 
	}
}
Output : 10

Example 3

public class A  {
	public static void main(String[] args) {
		A a1 = new A();
		a1.test();
		 
	}
	public void test() {
		int x=100;
		System.out.println(x);
	}
}
Output : 100

You Also Learn –

Example 4 : Without initializing the local variable we can not use that and hence the below program gone error

public class A  {
	public static void main(String[] args) {
	int x;
	System.out.println(x);  // Error
	}
}

Summary : Local variables are created inside the method and should be used only within the created method.

Leave a Comment