← Java from Scratch Lesson 26 of 88 · 10 XP

Scope

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Scope is where a variable exists:

  • local — declared in a method: visible from the declaration to the end of the method;
  • block — declared in { } (in an if, a for): visible only inside the block;
  • a class field — declared in the class outside the methods: visible to all the methods of the class.
public class Main {
    static int total = 0;                  // a field: lives while the program runs

    public static void main(String[] args) {
        int x = 5;                         // local
        for (int i = 0; i < 3; i++) {      // i is visible only in the loop
            int y = i * 2;                 // y — only in the loop body
        }
        // System.out.println(i);          // error: cannot find symbol
    }
}

In Java you can't declare a variable inside a block with the same name as a local variable outside it (variable x is already defined) — a protection against confusion.

Task. The program should count how many times hit() was called, but the counter is declared inside the method and gets reset every time. Fix it: move the counter into a class field. Print the final number of calls.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.