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 –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exceptions in Java
- What is inheritance in Java
- What is Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keyword in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
- What is Polymorphism in java
- What is non-static variable in java
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.