oopvariablesscopecomputer-scienceprincipal

OOP: Bounds of a variable's scope


Consider the following java code:

public class Main() {                           //Line 1
    public static void main(String[] args) {    //Line 2
        System.out.println("Hello World.");     //Line 3
                                                //Line 4
        int c = 10;                             //Line 5
        System.out.println(c);                  //Line 6
    }                                           //Line 7
}                                               //Loin 8

On what lines does the scope of variable c exist? Lines 2-7 or Lines 5-6?

This poses the question of whether or not a variable scope can precede the variable's declaration itself. Potentially, one can define scope as the area of code in which a variable can be used (Lines 5-6).

But this also raises the questions of whether scope is defined generically for all the variable's in a section of code (basically scope being defined by brackets) or if it's defined for each variable independently?

What's the proper interpretation of scope, and what's the justification for that interpretation?


Solution

  • Variable scope defines parts of code where a variable can be accessed. Java has a few different scopes. The one you're asking about is local variable block scope. Java has other scopes like class scope.

    Also Java Language Spec.

    Every declaration that introduces a name has a scope (§6.3), which is the part of the program text within which the declared entity can be referred to by a simple name.

    So it's not only about variables. Classes also are subject to this (e.g. are inner classes).

    As for your specific questions.

    scope is defined generically for all the variable's in a section of code (basically scope being defined by brackets)

    no, but

    defined for each variable independently

    yes each own variable not being visible to the code before its definition, so each of the scopes differ

    On what lines does the scope of variable c exist? Lines 2-7 or Lines 5-6?

    It's 5-6. If you'll write something like System.out.println(c) in line 3, the compiler will show you an error.