The following is a valid Java program:
public class _ {
public static void main(String[] args) {
{
{
{
{
}
}
}
}
}
}
Do those curly braces add extra semantics? Or are they treated just like whitespace?
The curly braces just create a local block scope inside your main method. The variables declared inside a block will not be visible outside.
This way of coding is used to minimize the scope of local variables.
It is a good practice to minimize the scope of the local variables you create, specially when you know they won’t be used anywhere else in your program. So, it doesn’t make sense to let it in the larger scope till it ends. Just create a local block scope, so that it will be eligible for
Garbage Collectionas soon as the block ends.Also see
@Bohemian'sanswer below that also quotes one more benefit.