love with java
love with java

Reputation: 123

Why is `main` called twice here?

Here is my code:

public class Test
{
   static 
   {
      main(null);
   }
   public static void main(String [] args)
   {
      System.out.println("done");
   }
}

I am getting the following output:

done 
done

Can somebody please explain me the reason for this?

Upvotes: 2

Views: 1904

Answers (7)

Niklas B.
Niklas B.

Reputation: 95328

The reason is that main is called twice:

  1. Explicitly, from the static initialization block as soon as the class is loaded.
  2. Implicitly, on program entry as soon as the program starts.

How to fix this? Either don't call it explicitly or rename it so that it won't be called automatically.

Upvotes: 6

quantum
quantum

Reputation: 3830

Main is automatically called by JVM. There is not need to call it in a static section.

public class Test
{
   public static void main(String [] args)
   {
      System.out.println("done");
   }
}

The above code is what it should be.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726829

Before calling Test.main, JVM needs to initialize the Test class by running its static initializer. This call is responsible for the first call of main(). Once the initialization is complete, JVM calls main() again, ultimately producing the output that you see.

Upvotes: 1

J_D
J_D

Reputation: 3596

The main is automatically called by the virtual machine when it loads the jar. So this is the first 'Done', the normal entry point for a Java program.

The second 'Done' is written because you explicitly call it in the static class initializer. The 'static' section that you added to your 'Test' class is called as soon as your class is loaded by the virtual machine class loader.

The one should from the static initializer even be called before the entry point Main is called, as the class needs to be loaded before the entry point is called.

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

What do you think unusual? The static block is executed once when the class is loaded (and it has to be loaded before executing main method. Then the main method itself is executed.

Check out this modified version:

public class Test {
    static {
        main(new String[]{"[done static]"});
    }

    public static void main(String[] args) {
        System.out.println(args.length > 0 ? args[0] : "[done]");
    }
}

It prints:

[done static]
[done]

Upvotes: 3

Jack
Jack

Reputation: 133609

Because

  • the static { ... } part is called when the class Test is loaded inside the JVM (it's a sort of static constructor)
  • while the main method is called when the execution begins.

Upvotes: 2

Rafa de Castro
Rafa de Castro

Reputation: 2524

The static block of a class is invoked when the class is first loaded. That is the first done. The second one is because you are running the program and then the main method is invoked.

Upvotes: 1

Related Questions