Why Is This Java Code in Curly Braces ({}) Outside of a Method

Why is this Java code in curly braces ({}) outside of a method?

Borrowed from here -

Normally, you would put code to initialize an instance variable in a
constructor. There are two alternatives to using a constructor to
initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static
initializer blocks, but without the static keyword:

{
// whatever code is needed for initialization goes here
}

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

You may also wanna look at the discussions here.

What does the '{' symbol (curly-brace) indicate in Java?

The question from your instructor seems not so great because there isn't a single unified meaning of the { symbol in Java.

In the context of a statement, the { symbol is used to denote the start of a block statement. This accounts for all the uses of { with if statements, while loops, for loops, do ... while loops, switch statements, etc., which technically only apply to a single statement but are often used with block statements:

if (x == 0) {
statementOne();
statementTwo();
}

In the context of a method or type (class/interface/enum/annotation), the { symbol is used to denote the beginning of the body of a class or a method:

public class NewClass {
...

public void foo() {
...
}
}

It can also be used inside a class to declare an initializer or static initializer block:

class MyClass() {
static int x;
static {
x = somethingHorrible();
}
};

In the context of an array literal, the { symbol is used to denote the beginning of the list of elements used inside that literal:

int[] arr = new int[] {1, 3, 7};

Each of these uses of the open brace symbol is different from all the others. In fact, the language would work just fine if we used a different symbol for each of these different contexts.

I think that the best answer to your question is that { is used in contexts where some group of things will be treated as a unit, whether it's a block statement (many statements treated as a single one), a class (many methods and fields treated as a single object), a method (many statements treated as a single unified piece of code), an initializer (many things that need to be done at once), etc.

In the majority of these contexts, as the comments have pointed out, the brace introduces a new scope. Statement blocks, class bodies, initializer bodies, and function bodies all introduce a new scope, and that is definitely something important to keep in mind. (Array initialization doesn't do this, though.)

java just curly braces

It's a code block. The variables declared in there are not visible in the upper block (method body outside of these curlies), i.e. they have a more limited scope.

What do curly braces in Java mean by themselves?

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.

What is the purpose of the {} outside of any methods?

Is there any practical use of this?

There is one "idiom" that makes use of instance initializer blocks:

 Map mymap = new HashMap() {{put("a", 1); put("b", 2);}};

This is a concise way to create a map that is initialized with a given set of entries. And when you break it down, it is declaring and instantiating an anonymous subclass of HashMap which uses an instance initializer block to populate the new map.


My impressions are: it seems working, but smells like bad and strange practice.

That's a subjective statement. The only rational argument I can think of for initializer blocks being bad / strange is that people don't use them. And that argument smells of circular logic.

Does extra braces inside a method have any usage?

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.

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 copy and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.

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.

Generate colors between red and green for a power meter?

This should work - just linearly scale the red and green values. Assuming your max red/green/blue value is 255, and n is in range 0 .. 100

R = (255 * n) / 100
G = (255 * (100 - n)) / 100
B = 0

(Amended for integer maths, tip of the hat to Ferrucio)

Another way to do would be to use a HSV colour model, and cycle the hue from 0 degrees (red) to 120 degrees (green) with whatever saturation and value suited you. This should give a more pleasing gradient.

Here's a demonstration of each technique - top gradient uses RGB, bottom uses HSV:

http://i38.tinypic.com/29o0q4k.jpg

Placing arbitrary braces as statements - what do they mean?

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.

public void someMethod() {
{
int x = 10;
System.out.println(x); // Ok
}
System.out.println(x); // Error, x not visible here
}

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 Collection as soon as the block ends.

Also see @Bohemian's answer below that also quotes one more benefit.

Can I write a method body without curly braces {}?

Curly braces are required for methods.

From the Java Language Specification:

Method Body

A method body is either a block of code that implements the method or
simply a semicolon, indicating the lack of an implementation.

What is a block?

A block is a sequence of statements, local class declarations, and
local variable declaration statements within braces.

Also required for classes.

Class Body and Member Declarations

ClassBody:
{ {ClassBodyDeclaration} }

*Bold formatting is mine.



Related Topics



Leave a reply



Submit