Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Scope

Java Scope

In Java, variables are confined to the region where they are declared, known as their scope.

Method Scope

Variables declared within a method are accessible throughout the method’s entirety beyond the line of code where they’re declared.

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

A code block encompasses all the code enclosed within curly braces { }.

Variables declared within code blocks are only accessible within the block of code enclosed by curly braces, following the line where the variable was 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

  }
}

 

A code block can stand alone or be associated with an ifwhile, or for statement. In the case of for statements, variables declared within the statement itself are also accessible within the block’s scope.