Skip to content
Advertisement

What is ‘scope’ in Java?

I just started coding. I want to use a switch statement twice for the same variable, and I was told that to do this the variable would have to be ‘in scope’.

Being a beginner, I have no idea what that means. So what does being in scope mean? And, if a variable isn’t in scope, how do I make it in scope?

Advertisement

Answer

A local variable1 is “in scope” if code can access it and out of scope if it can’t. In Java, variables are scoped to the block ({}) they’re declared in. So:

void foo() {
    int a = 42;

    if (/*some condition*/) {
        String q = "Life, the Universe, and Everything";

        // 1. Both `a` and `q` are in scope here
        System.out.println(a);
        System.out.println(q);
        if (/*another condition*/) {
            // 2. Both `a` and `q` are in scope here, too
            System.out.println(a);
            System.out.println(q);
        }
    }

    // 3. Only `a` is in scope here
    System.out.println(a);
    System.out.println(q); // ERROR, `q` is not in scope
}

Note (1), (2), and (3) above:

  1. The code can access q because q is declared in the same block as the code; tt can access a because it’s declared in the containing block.

  2. The code can access q because it’s declared in the containing block; it can access a because it’s in the next block out.

  3. The code can access a, but not q, because q isn’t declared in the block or any of the blocks (or a couple of other things) containing it.

When figuring out what an unqualified identifier (like a or q above, as opposed to the foo in this.foo or the toLowerCase in q.toLowerCase, which are qualified) is, the Java compiler will look in each of these places, one after the other, until it finds a match:

  • For a variable with that name in the innermost block
  • For a variable with that name in the next block out, and so on
  • For a field2 or method (generally: member) with that name in the current class
  • For a class with that name from a package that’s been imported
  • For a package with that name

There are a few others for that list (I’m not going to get into static imports with a beginner).

There’s a lot more to scope, I suggest working through some tutorials and/or a beginning Java book for more.


1 “local variable” vs. “variable” – The Java Language Specification uses “variable” in a more general way than most people do in common speech. When I say “variable” in this answer, I mean what the JLS calls a “local variable”.

2 “field” – The JLS calls fields “variables” in some places (and “fields” in other places), hence (1) above. 🙂

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement