-7

FYI - Here is only one class file FirstDup. Question- As we know that static block get executed only once when class is loaded in JVM. So my point is.. when I start the execution of class by giving the command "java FirstDup" then class is loading and then immediately static block get executed. But thereafter when control comes to "public static void main()" to create first object s1 then why static blocks are executing again while class has already been loaded just after giving "java FirstDup" command? Please help me on this and correct me if I am saying anything wrong.

public class FirstDup {

    public FirstDup() {
        System.out.println("Constructor running");
    }

    {
        System.out.println("1st Non-static running");
    }

    {
        System.out.println("2nd non-static running");
    }

    static{
        System.out.println("1st static running");
    }

    static{
        System.out.println("2nd static running");
    }

    public static void main(String[] args) {
        System.out.println("Main method running"); 
        SampleFirst s1 = new SampleFirst();
        SampleFirst s2 = new SampleFirst();

    }

}

....... output

1st static running
2nd static running
Main method running
1st static running
2nd static running
1st Non-static running
2nd non-static running
Constructor running
1st Non-static running
2nd non-static running
Constructor running
Slaw
  • 37,820
  • 8
  • 53
  • 80
Rani
  • 1
  • 2
    I can't reproduce that behavior, though I had to change some things about your example—specifically, changing `SampleFirst` to `FirstDup`. So if you are getting the output you say you are then the problem is in `SampleFirst` (if that's a real class). – Slaw Apr 02 '19 at 03:03
  • 1
    I assume you have same static blocks in `SampleFirst` class as you have in `FirstDup` class? – Kartik Apr 02 '19 at 03:03

1 Answers1

2

It runs only once for FirstDup. The second set of "static running" statements must be coming from SampleFirst class. I bet you have the same set of constructor, static and init blocks in the SampleFirst class.

Kartik
  • 7,677
  • 4
  • 28
  • 50