What do curly braces in Java mean by themselves?

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?

The only purpose of the extra braces is to provide scope-limit. The List<PExp> copy will only exist within those braces, and will have no scope outside of them.

If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a List<PExp> copy and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.

The answer is twofold: In a Java program, curly braces enclose meaningful units of code. You, the programmer, can (and should) indent lines so that other programmers can see the outline form of your code at a glance. In an outline, everything is subordinate to the item in Roman numeral I.

I second what matt b wrote, and I'll add that another use I've seen of anonymous braces is to declare an implicit constructor in anonymous classes. For example:

  List<String> names = new ArrayList<String>() {
    // I want to initialize this ArrayList instace in-line,
    // but I can't define a constructor for an anonymous class:
      {
        add("Adam");
        add("Eve");
      }

  };

Some unit-testing frameworks have taken this syntax to another level, which does allow some slick things which look totally uncompilable to work. Since they look unfamiliar, I am not such a big fan myself, but it is worthwhile to at least recognize what is going on if you run across this use.

What do curly braces in Java mean by themselves? (this is the one some claim that it should be closed as duplicated of) The only purpose of the extra braces is to provide scope-limit. The List copy will only exist within those braces, and will have no scope outside of them. Why is this Java code in curly braces ({}) outside of a method?

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.

In javascript curly braces are used for several purposes. I your case these are used to create a key-value pair. In others cases curly braces are used to combine a set of statements in a block. And sometimes they are used to create objects like var abc = { "a": 1, "b": 2 };

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.

What do curly braces in Java mean by themselves? 1438. Fastest way to determine if an integer's square root is an integer. 492. How to nicely format floating numbers

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

2 i believe like other languages curly braces are just a way of telling the compiler/code interpreter that you have sectioned off multiple lines into a particular scope. Scope meaning the area that the current running code has access to variables, functions, and other resources declared inside the current "scope". share | improve this answer

I would not use curly braces for that purpose for a couple reasons. If your particular function is big enough that you need to do various scoping tricks, perhaps break the function into smaller sub-functions. Introducing braces for scoping to reuse variable names is only going to lead to confusion and trouble in code.

synchronized (foo) { int version = foo.getVersion(); String content = foo.getContent(); } // Do something with version and content The problem is that in this version the variables are defined in the scope of the (synchronized) curly braces and can therefore not be accessed outside of the block.

Do you use curly braces for additional scoping? I mean other than using it when required for functions, classes, if, while, switch, try-catch. I didn't know that it could be done like this until I saw this SO question.

Comments
  • An additional "benefit" in this case is that copy can be garbage collected before outAMethodExp() returns. If this is a long-running or memory-intensive call, that may be helpful. I put "benefit" in quotes because refactoring into separate methods is generally much cleaner and clearer than taking advantage of this syntax.
  • Actually, scoping a variable does not have an effect on garbage collection. In all modern JVMs I'm aware of, the JIT can determine that an object is eligible for GC regardless of the presence or absence of scoping constructs like braces.
  • I am sorry, I don't understand this code. Is "add" a class or a function. If it is a function: what class does it belong to? Is ArrayList accepting a delegate type in this case?
  • "add" is a function. The stuff within the curly braces gets called before the constructor to perform some preliminary initialization. You can check out c2.com/cgi/wiki?DoubleBraceInitialization for more.
  • Technically, the constructor gets called first and the instance initialization block gets called immediately after the call to super(...).
  • I'm voting you up simply because it can happen, has happened, and Occam is rolling in his grave because you were voted down. :)
  • It is generated by SableCC. I bet 5$ they did not forget else
  • Additional braces are useful for preventing global variables from creeping up on you in a long method where you want to keep a few, similar code blocks all in the same spot, where the blocks aren't complex enough to warrant new methods.
  • I mark java coursework at a university, and can see that this is actually often the exact reason why it is found in code. When re factoring people sometimes cut/paste and then see the wrong number of braces,.. just add one in.. then look what you end up with. For that reason I am up voting this. Not always an else statement, but often just a simple mistake.
  • I upvoted you because -1 votes means you should not have even participated. Maybe you didn't know, but you put in an effort. I'm not about trophies for everyone, but "thanks" is just what I say to people who are trying to help. (+1 == thanks).
  • Probably worth mentioning that this is only for static class initialization outside the constructor. OPs code snippet is in a method block (only possible place for it).
  • An initialization block is for static class initialization if it is prefaced with static otherwise its an instance initialization block.