Scope in Java
Scope In Java
Scope of a variable is the part of the program where the variable is accessible. Variables are only accessible inside the bracket {} they are created.
Method Scope
If we created variables inside the method, we could use them inside but not outside the method.
public class Main {
public static void main(String[] args) {
System.out.println(a); // this is wrong we cannot use a here
}
public static void myMethod() {
int a = 10;
System.out.println(a); // we can use a here
}
}
Block Scope
Block means code between {} brackets. Variables are only accessible inside the bracket {}.
public class Main {
public static void main(String[] args) {
System.out.println(a); // this is wrong we cannot use a here
{
int a = 10;
System.out.println(a); // you can use it here.
}
}
}