31

I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests:

class Foo {  
    int x = 1;  
    public static void main(String [] args) {  
        int x = 2;  
        Foo f = new Foo();  
        f.whatever();  
    }  
    { x += x; }  // <-- what's up with this?
    void whatever() {  
        ++x;  
        System.out.println(x);  
    }  
}

My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?

mchen
  • 9,808
  • 17
  • 72
  • 125
nairdaen
  • 1,037
  • 2
  • 11
  • 19
  • 3
    See also [8.6 Instance Initializers](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6). – trashgod May 03 '11 at 04:43
  • Stephen, it might be duplicate because of the topic but I got this in an entirely different way – nairdaen May 03 '11 at 04:52
  • 3
    Yes valid, as others have pointed out. However, at some point in your life you will be programming after you get your Java certification. Please, never use this structure in your everyday work. Please. I HATE the Java Certification. It teaches you all kinds of disturbingly convoluted, and sometimes subtel, ways to confuse your co-workers and introduce bugs. – rfeak May 03 '11 at 05:17
  • @rfeak agreed. It's hard to read, so don't use it, and if you do, then provide lots of comments. – Rob Grant Sep 25 '14 at 06:35
  • hii.. @nairdaen i am also want to start study for java oracle certification, so do have any notes, practice tests and programs, questions, web links or any other study material and can you provide me that would be very helpful thanks – Arsh Kaushal May 29 '17 at 10:37

3 Answers3

37

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.

Community
  • 1
  • 1
Shankar Raju
  • 4,356
  • 6
  • 33
  • 52
  • 1
    I have one question why this code never executed then.... { System.out.println("com.test.BaseClazz. initial"); } – Omer Dec 01 '16 at 21:31
14

This is an initializer block that is executed while the instance of the class is being loaded/created and that is used to initialize member properties of a class (See Java http://download.oracle.com/javase/tutorial/java/javaOO/initial.html). You can have as many blocks as you want and they will be instantiated from top to bottom.

In addition to the instance block, you can have as many static blocks as you want as well to initialize static members. They would be declared as follows:

public class Initialization {

    static int b = 10;

    int a = 5;

    static {
        b = -9;
    }

    {
        a += 2;
    }

    public static void main(String[] args) throws Exception {

        System.out.println(ClientVoting.b);
        System.out.println(new ClientVoting().a);
        System.out.println(ClientVoting.b);
        System.out.println(new ClientVoting().a);

    }

    static {
        b = 1;
    }

    {
        a++;
    }
}

While the class is being initialized, the static member "b" is initialized as 10, then the first static scope changes its value to -9, and later to 1. This is only executed once while the class is loaded. This executes before the initialization of the first line of the main method.

On the other hand, the similar example to your class is the instance reference "a". A is initialized as 5, then the instance block updates it to 7, and the last block to 8. As expected, the static members are only initialized once in this code, while the instance blocks are executed EVERY time you create a new instance.

The output to this example is 1 8 1 8

一二三
  • 21,059
  • 11
  • 65
  • 74
Marcello DeSales
  • 21,361
  • 14
  • 77
  • 80
9

It's an initializer block. It's used to set instance variables. The motivation to use initializer blocks over constructors is to prevent writing redundant code. The Java compiler copies the contents of the block into each constructor.

blackcompe
  • 3,180
  • 16
  • 27