Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 501
Paul Wicks Avatar asked Oct 27 '08 19:10

Paul Wicks


People also ask

What is the meaning of {} in Java?

In Java when you open a curly brace it means that you open a new scope (usually it's a nested scope).

What is {} called in programming?

What Does Bracket Mean? Brackets, or braces, are a syntactic construct in many programming languages. They take the forms of "[]", "()", "{}" or "<>." They are typically used to denote programming language constructs such as blocks, function calls or array subscripts. Brackets are also known as braces.

What are braces used for in Java?

Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.


1 Answers

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.

like image 74
matt b Avatar answered Sep 25 '22 16:09

matt b