Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the rationale behind this code block in java?

People also ask

What is a code block in Java?

Another key element of Java is the code block. A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can.

Why blocks are used in Java?

A block statement is a sequence of zero or more statements enclosed in braces. A block statement is generally used to group together several statements, so they can be used in a situation that requires you to use a single statement.

What is used in Java to surround code blocks?

Java try block is used to enclose the code that might throw an exception. It must be used within the method. If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception.

How are blocks of code demarcated in Java?

Program code in a Java program is contained in a block. A block begins with an open curly brace symbol and ends with a close curly brace symbol. As an example, we might write a block of code that contains a variable definition and some console print statements.


One point is that it will execute whichever constructor is called. If you have several constructors and they don't call each other (for whatever reason, e.g. each wanting to call a directly-corresponding superclass constructor) this is one way of making sure the same code is executed for all constructors, without putting it in a method which could be called elsewhere.

It's also potentially useful when you're writing an anonymous class - you can't write a constructor, but you can write an initializer block. I've seen this used for JMock tests, for example.


It's called an initializer block.

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


It called init block. In such block you can perform logic that are same for all constructions also you can separate declaration and initialization of same fields.

upd and of course double brace initialization, like

List<Integer> answers = new ArrayList<Integer>(){{add(42);}}

This is an initialization block. As mentioned by Matt Ball, they are copied into each constructor.

You might be interested to know about static initialization blocks (also in Matt's link):

public class Foo {
    static {
        System.out.println("class Foo just got initialized!");
    }

    {
        System.out.println("an instance of Foo just got initialized!");
    }
}