SCOPE IN JAVA
In Java, variables are only accessible inside the region they are created. This is called scope.The scope of a variable, method, or object is determined by where it is declared in the code of a program.
Types of scopes in java:
1. Class level scope
2. Instance level scope
3. Local scope
4. Block scope
Class level scope:
A variable, method, or object declared as static has class level scope. It can be accessed anywhere within the class and can also be accessed without creating an instance of the class.
Instance level scope:
A variable, method, or object declared within a class, but not static, has instance level scope. It can be accessed within any method or block of code within an instance of the class.
Local scope:
A variable declared within a method has local scope. It can be accessed only within the method in which it is declared.
Block scope:
A variable declared within a block of code, such as a loop or conditional statement, has block scope. It can be accessed only within that block of code.
Example:
public class Main
{
public static void main(String[] args)
{
// Code here cannot use x
int x = 500;
// Code here can use x
System.out.println
(x);
}
}
Output:
500