{ // Open brace starts block } // Close brace ends blockThis does nothing, and just like using a semicolon.
{ // Open brace starts block System.out.println( "One" ) ; } // Close brace ends block
{ // Open brace starts block System.out.println( "One" ) ; System.out.println( "Two" ) ; System.out.println( "Three" ) ; } // Close brace ends block
For example:
public void foo() { int x = 3 ; { // Open brace starts block int y = 4 ; // Prints 7. y is accessible here System.out.println( "Sum is " + (x + y) ) ; } // End of block. y is out of scope System.out.println( "x is " + x ) ; // Won't compile. y is not in scope System.out.println( "Sum is " + (x + y) ) ; }We started a block and within the block we declared y. y is created at the declaration. It disappears once we exit the end of the block. Thus, the very last println() fails to compile because y is not in scope. It's only valid within a block.
The block is often called the inner scope. The method body is then the outer scope. If you can't find the variable you're looking for in the inner scope, then you look at the outer scope. This is how x is found. When you start a block, it has access to all variables as if you had never started the block. When you exit a block, the variables in the block are invalid.
public void foo() { int x = 3 ; { // Open brace starts block boolean x = true ; // Prints "x is true" System.out.println( "x is " + x ) ; } // End of block. y is out of scope // Prints "x is 3" System.out.println( "x is " + x ) ; }When you enter a block, you enter a scope. If you declare a variable with the same name as an outer scope, then the inner variable is used, and the variable in the outer scope is shadowed or hidden. Even though Java permits this, it's usually a bad idea to shadow variables.
When x is declared in the block as a boolean variable, the other x, which is declared as an int variable still exists. There are two different x variables. However, you can only access the x that's closest in scope to you.
Thus, the first println() method picks the boolean x, since that println() is in the block where the boolean x was declared.
In the second println(), the boolean x is out of scope, and is no longer valid. Thus, the only available x is the int version, which still has a value of 3, showing that it did not disappear.
First, the method body is itself a block. Local variables in the method body are created upon entering the block (and running the declaration) and disappear when one exits the method body.
Second, once we talk about control flow, we'll see blocks everywhere. It's strange now, but it's something you have to deal with.