What is the difference between scope and block?

后端 未结 9 1069
旧巷少年郎
旧巷少年郎 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 05:59

    a scope is where you can refer to a variable. a block defines a block scope a variable defined inside a block will be defined only inside that block and you can't reference it after the end of block.

    so in this code if you try something like:

    x = 10;
    if(x ==10) { // start new scope
    int y = 20; // known only to this block
    x = y * 2;
    }
    
    y = 5; // error y is out of scope, not it is not defined
    

    because what you have here is a local scope
    other kinds of scope in java are class scope (for example), a member of a class has a class scope so it is accessible anywhere inside a class.

    the basic rules for scope are:

    1. The scope of a parameter declaration is the body of the method in which the declaration appears.
    2. The scope of a local-variable declaration is from the point at which the declaration appears to the end of that block.
    3. The scope of a local-variable declaration that appears in the initialization section of a for statement’s header is the body of the for statement and the other expressions in the header.
    4. A method or field’s scope is the entire body of the class. This enables non-static methods of a class to use the fields and other methods of the class.

提交回复
热议问题