Java Scope


Java Scope

In Java, variables are only accessible within the region created. This is called scope.


Method Scope

The variables declared directly within the path are available anywhere along the line following the declared line:


Example
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

Code block means all code between folded parentheses {}. The declared variables within the code blocks are only accessible by code between the folded parentheses, following the line where the variable is declared:


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
          
            }
          }

The code block can be either if, while or for statement. In the case of for statements, the variables declared in the statement itself are also found within the width of the block.