What is the difference between scope and block?

when it comes to conditions and loops if you don't specify {} then immediate following statement is the only statement that will belong to particular condition or loop

e.g.

x = 10;
if(x ==10) 
{ 
int y = 20; 
x = y * 2;
}
both lines get executes only if condition returns TRUE

x = 10;
if(x ==10) 
int y = 20;
x = y * 2; // this is not belong to if condition. therefore it will execute anyway

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.

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.

Tags:

Java