Java Scope

Java Scope

In Java, scope refers to the visibility of variables. In other words, which parts of your program can see or use a certain variable.

Variables are only accessible inside the region they are created. This is called scope.


Method Scope

Variables declared directly inside a method are available anywhere in the method from the point at which they are declared.

Method Scope Example

public class Main {
  public static void main(String[] args) {
    // x can be used in this method
    int x = 100;
    System.out.println(x);

} }


Block Scope

A block of code refers to all of the code between curly braces {}.

Variables declared inside a block of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared.

Block Scope Example

public class Main {
  public static void main(String[] args) {
    // Code here CANNOT use x
    { // This is a block
      // Code here CANNOT use x
      int x = 100;
      // Code here CAN use x
      System.out.println(x);
    } // The block ends here
    // Code here CANNOT use x

} }

A variable declared in a block is only available inside that block. Trying to access it outside the block will result in a compilation error.