Utilizor
Contact Us

Java Scope

Variable accessibility.

Examples

Method Scope

x is only available after declaration inside main.

public class Main {
  public static void main(String[] args) {
    // Code here CANNOT use x

    int x = 100;

    // Code here can use x
    System.out.println(x);
  }
}

Block Scope

x is only available inside the {} block.

public class Main {
  public static void main(String[] args) {
    // Code here CANNOT use x

    { // This is a block
      int x = 100;
      // Code here can use x
      System.out.println(x);
    } // The block ends here

  // Code here CANNOT use x
  }
}

Test Your Knowledge

Java Quiz

No quiz available for this topic yet.