-1

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
    Your code doesn't compile. Please show a complete, runnable example which illustrates your question. – tgdavies Jul 16 '22 at 08:04
  • `import java.util.Scanner; public class TestingInitializiingBlock { public static void main(String[] args) { System.out.print("Enter: "); Scanner scan = new Scanner(System.in); if (scan != null) { { System.out.println("im initializing block into if statement!"); } } } } ` This is just example of issue. copy code and try yourself – Vahobjon Tolibov Jul 16 '22 at 08:49
  • What behaviour do you see that you are unsure about? – tgdavies Jul 16 '22 at 09:41
  • @VahobjonTolibov Do not add code in a comment, use the [edit] link to edit your question and add the code there. – Progman Jul 16 '22 at 09:55

1 Answers1

1

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.

Mirek Pluta
  • 7,883
  • 1
  • 32
  • 23