What do curly braces in Java mean by themselves?

2019-01-04 23:47发布

I have some Java code that uses curly braces in two ways

// Curly braces attached to an 'if' statement:
if(node.getId() != null)
{
    node.getId().apply(this);
}

// Curly braces by themselves:
{
    List<PExp> copy = new ArrayList<PExp>(node.getArgs());
    for(PExp e : copy)
    {
        e.apply(this);
    }
}
outAMethodExp(node);

What do those stand-alone curly braces after the first if statement mean?

11条回答
男人必须洒脱
2楼-- · 2019-01-05 00:20

It is also used for initialization blocks.

查看更多
SAY GOODBYE
3楼-- · 2019-01-05 00:21

They make an inner scope. Variable declared inside these braces is not visible outside of them. This also applies to C/C++.

查看更多
Fickle 薄情
4楼-- · 2019-01-05 00:22

I agree with the scope limit answer, but would add one thing.

Sometimes you see a construct like that in the code of people who like to fold sections of their code and have editors that will fold braces automatically. They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up.

查看更多
迷人小祖宗
5楼-- · 2019-01-05 00:24

The bring a scope, copy will not be visible outside of it, so you can declare another variable with same name later. And it can be gathered by the garbage collector right after you exit that scope. In this case copy serves as a temporary variable, so it is a good example.

查看更多
爷、活的狠高调
6楼-- · 2019-01-05 00:25

I'd actually guess that someone forgot an else statement.

There's rarely a good reason to even bother with creating additional block scopes. In this, and most cases, it's far more likely someone may have forgotten to type their control statement than it is that they were doing something clever.

查看更多
We Are One
7楼-- · 2019-01-05 00:26

Braces are also useful to reduce the scope in switch/case statements.

switch(foo) {
  case BAR:
     int i = ...
     ...
  case BAZ:
     int i = ... // error, "i" already defined in scope
}

But you can write

switch(foo) {
  case BAR:{
     int i = ...
     ...
  }
  case BAZ:{
     int i = ... // OK
  }
}
查看更多
登录 后发表回答