Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block Statements in Java

Tags:

java

block

I have a class MyMap which extends java.util.HashMap, the following code works as a block of statements but I don't understand the use of the extra curly braces

MyMap m = new MyMap() {
  {
      put("some key", "some value");
  }
};

Now why do I need the extra curly braces, can't I just do this (but this raises compile error)

MyMap m = new MyMap() {
    put("some key", "some value");
};
like image 754
K'' Avatar asked Aug 24 '11 20:08

K''


People also ask

What is block in Java with example?

A block in Java is a set of code enclosed within curly braces { } within any class, method, or constructor. It begins with an opening brace ( { ) and ends with an closing braces ( } ). Between the opening and closing braces, we can write codes which may be a group of one or more statements.

What is block and method in Java?

Blocking methods in java are the particular set of methods that block the thread until its operation is complete. So, they will have to block the current thread until the condition that fulfills their task is satisfied. Since, in nature, these methods are blocking so-called blocking methods.

What are the statements in Java?

Java supports three different types of statements: Expression statements change values of variables, call methods, and create objects. Declaration statements declare variables. Control-flow statements determine the order that statements are executed.

What is the difference between a statement and a block?

A block is a type of statement that contains declarations and other statements surrounded by braces { int i = 1; System. out. println(i); } . Some statements are built using other statements.


2 Answers

This:

MyMap m = new MyMap() {
    ....
};

creates an anonymous inner class, which is a subclass of HashMap.

This:

{
    put("some key", "some value");
}

is an instance initializer. The code is executed when the instance of the anonymous subclass is created.

like image 165
Richard Fearn Avatar answered Sep 23 '22 15:09

Richard Fearn


What you're actually doing here is define an anynomous subclass of MyMap, which was probably not your intent... The outermost curly braces are around the class contents. And in Java, you cannot put instructions directly inside a class block: if you need code to be executed when the class is instantiated, you put it into a constructor. That's what the innermost braces are for: they delimit an initializer for your anonymous class.

Now, you probably wanted something like:

MyMap m = new MyMap();
m.put("some key", "some value");

Just create an instance of MyMap and call put on it, no anonymous class involved.

like image 23
ChrisJ Avatar answered Sep 22 '22 15:09

ChrisJ