demdem
demdem

Reputation: 182

What does double initialization mean in Java methods

I only use double initialization in java for classes ex:new ArrayList(){{add()}} But I recently wrote a code as below by mistake and JVM did not get angry for my mistake.

public void test(){
    {
        {
            ....
        }
    }
}

After that made a simple example and saw the following but still didn' t understand anything expect order of running statements.

public class HelloWorld{

     public static void main(String []args){
        HelloWorld hw=new HelloWorld();
        hw.test1();
        System.out.println("----------");
        hw.test2();
     }

    public void test1(){
        {
            {
                System.out.println("1");
            }
            System.out.println("2");
        }
        System.out.println("3");
    }

    public void test2(){
        System.out.println("a");
        {
            System.out.println("b");
            {
                System.out.println("c");
            }

        }

    }
}

Result:

1
2
3
----------
a
b
c

So my question is that what does double or triple etc initializations mean in Java?

Upvotes: 2

Views: 52

Answers (1)

GBlodgett
GBlodgett

Reputation: 12819

This is not double brace initilization. This is a block statement. From the docs:

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

A block statement encloses the statements within it in a different scope. So if you did:

public static int foo() {
    {
        int foo = 0;
    }
    return foo;
}

foo would not be in scope in the line return foo; and you would get an error


In your code, these nested blocks make no difference, as you are just printing, but each block will have a different scope

Upvotes: 4

Related Questions