Concept of Scope of variables in Java
In Java scope of a variable is the section of the program where the variable is attainable inside the area where they are created. Like C/C++, in Java, all identifiers are logical or statical examine, i.e.scope of a variable can be set at compile-time and independent of the function call stack.
Method of Scope in Java
In Java, the scope defines a secure variable method or a method public in a program. Variables can be defined as having one of three types of scope:
Variables apparent straight inside a method are available anywhere in the method pursuing the line of code in which they were declared:
Class level scope is the instance variables where variable declared within a class or inside a class where it is accessible by all methods in that class. Depending on its access modifier (ie. public or private), sometimes it can be accessed outside the class.
public class Main {
public static void main(String[] args) {
// Code here cannot use a
int a = 80;
// Code here can use a
System.out.println(a);
}
}
Method level scope is local variables any variable which is declared within a method, arguments included, is NOT available outside that method.
public class Main
{
static int a = 16;
private int b = 39;
public void method1(int a)
{
Main t = new Main();
this.a = 22;
b = 44;
System.out.println("Main.a: " + Main.a);
System.out.println("t.a: " + t.a);
System.out.println("t.b: " + t.b);
System.out.println("b: " + b);
}
public static void main(String args[])
{
Main t = new Main();
t.method1(5);
}
}
Block scope or a block of code variables are loop variables that are declared inside blocks of code are only available by the code between the curly braces,
public class Main {
public static void main(String[] args) {
// Code here cannot use a
{ // This is a block
// Code here cannot use a
int a = 500;
// Code here CAN use a
System.out.println(a);
} // The block ends here
// Code here cannot use a
}
}