Braces and Blocks

Let’s investigate the Hello World program a little more closely. In Java a source code file is broken up into parts separated by opening and closing braces, i.e. the { and } characters. Everything between { and } is a block and exists more or less independently of everything outside of the braces.

Blocks are important both syntactically and logically. Without the braces the code wouldn’t compile. The compiler would have trouble figuring out where one method or class ended and the next one began. Similarly it would be very difficult for someone else reading your code to understand what was going on. For that matter it would be very difficult for you, yourself to understand what was going on. The braces are used to group related statements together. In the broadest sense everything between matching braces is executed as one statement (though depending not necessarily everything inside the braces is executed every time).

Blocks can be hierarchical. One block can contain one or more subsidiary blocks. In this case we have one outer block that defines the HelloWorld class. Within the HelloWorld block we have a method block called “main”.

In this tutorial we help to identify different blocks with indentation. Every time we enter a new block we indent our source code by two spaces. When we leave a block we deindent by two spaces. This is a common convention in many programming languages. However it is not part of the language. The code would produce identical output if we didn’t indent it. In fact I’m sure you’ll find a few examples here where I haven’t followed convention precisely. Indentation makes the code easier to read and understand, but it does not change its meaning.

click here to read

Comments are closed.