What is the difference between scope and block?

后端 未结 9 1073
旧巷少年郎
旧巷少年郎 2021-01-04 05:16

I saw a piece of code in a book, which is as follows:

x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}

9条回答
  •  再見小時候
    2021-01-04 06:01

    From the Java language specification:

    14.2. Blocks:

    A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.

    6.3. Scope of a Declaration

    The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).

    In a block, you can declare variables. A scope defines the region, where you can access a declared variable by its simple name.

提交回复
热议问题