Using initializing blocks into conditional statements

36 views Asked by At

I've tested the scenario with initializing blocks, the problem is that if we declare initializing block into if conditional or other conditional statements, initializing block runs first when object initializes.

What the purpose of using initializing block into conditional statements if it runs whatever firstly.


        Scanner scan = new Scanner(System.in);
        if (scan != null) {
            {
                System.out.println("im initializing block into if statement!");
            }   }}

Output:

Enter: im initializing block into if statement!

1

There are 1 answers

0
Mirek Pluta On

Initializing blocks can be only defined on the class level, not inside method. What you have in here is just a block scope, nothing else.