Scope

Java supports following scopes:

  • package scope - everything that declared inside package
  • class scope - everything that declared inside class; it is splitted to static and instance scopes
  • local scope - everything that declared inside method of class
  • block scope - anything declared inside the curly brackets {} or the Java statement body

Java does not allow variables and functions outside of classes or interfaces.

package scope

A package is a mechanism for grouping classes and interfaces. Package directly mapped to the folder on file system, so you can think about package as directory. If, for example, libraries have the same package name, Java will treat them as one package. In other words, the classes inside them will be union into one package.

For using a public class or interface from another package you need make import at the begin of file. All serious IDEs do this automatically.

Package example
//----------------------------------------
// syntax of import single item of package
// and import whole package
/*
import package.name.ClsName;
import package.name.*; 
*/

static scope

A public static member accessible outside of class via class name with the dot operator.

With special static import you can use static members of other class directly.

import static java.lang.Math.*; 

class Demo { 
  public static void main(String[] args) { 
    // sqrt is used  directly instead Math.sqrt
    System.out.println(sqrt(4)); 
    System.out.println(pow(2, 2)); 
    System.out.println(abs(3.14)); 
  } 
}

instance scope

An instance scope will be append to corresponded class scope. This means you can not declare static member and non-static member with same name.

A public member accessible outside of class via object with the dot operator.

System.out.println(abs(3.14)); 

local scope

Parameters of method and variables declared inside method are called local variables of method. You can not access to them outside of method.

Local variables will shadow same names from outer scope.

Code example

block scope

Block variables will shadow same names of class members.

You can declare the same name in separate blocks, but not in nested blocks.

public class Demo {
  
  public  int data = 100;

  void method(){
    // int data = -10;

    {
      int data = 10;
      System.out.println(data); // 10
    }
    {
      int data = 20;
      System.out.println(data); // 20

      {
        //  int data = 30;
             
       }

     }
  }
}