1

I'm having difficulties in finding a duplicate or explanation, as I don't know the name for the syntax.

Earlier today, I wrote a piece of code containing an extra ;:

if (condition); {
    try {
        // something
    } catch (Exception e) {
        // something
    }
}

I know that the if statement is interrupted by the ;. What I'm interested in is the block

{
    // something
}

How is that block ({}) without a leading if, for, ... called, and what can I use it for?

baao
  • 71,625
  • 17
  • 143
  • 203

3 Answers3

3

You can use {} blocks on their own, you don't (necessarily) need if, else or other keywords for that.

Such blocks are useful to structure code or, for instance, to limit scopes of local variables, ex.:

{
     int myVar = ...;
}

myVar will not be visible/accessible outside of the block so that might make it easier to read this code as you don't have to consider myVar outside of the block.

lexicore
  • 42,748
  • 17
  • 132
  • 221
3

It is called (Anonymous) Code Block.

There is an SO post on the motivation of the feature.

Anonymous code blocks in Java

Community
  • 1
  • 1
leeyuiwah
  • 6,562
  • 8
  • 41
  • 71
1

It is simply a compound statement. The reason your typo is not a syntax error is that an if statement, by definition, is followed by exactly one statement. That could be an empty statement (;), a simple statement (x = x + 1), or a compound statement ({ ... }).

A compound statement by itself (rather than being used as the body of and if, for, etc) is typically used to define a scope in which a variable can be defined with a precise life span.

// No foo out here
{
   int foo;
   ...
}
// No foo here either
chepner
  • 497,756
  • 71
  • 530
  • 681