Vijin Paulraj
Vijin Paulraj

Reputation: 4648

Will a static block execute without the main method?

I'm trying to run the below code on my machine, but it didn't execute anything nor showing any errors.

public class StaticBlockDemo {
    static {
        System.out.println("Hello World");
    }
}

Can someone please help me? By the way, I'm using Java 7.

Upvotes: 22

Views: 15719

Answers (6)

ankita
ankita

Reputation: 11

abstract class test extends javafx.application.Application {
    static {
        System.out.println(“hello”);
        System.exit(0);
    }
}

Compile using : javac -source 1.6 test.java

Run using : java test

This will even work with JDK 1.8. 🙂

Upvotes: 1

In java 8 you can not run a program without explicitly write a main method. From this angle the answer false. Static block is not executed without main method.Below is a piece of code which shows the order of initializaion .(Static block==>main==>initialization block==>constructor)

public class StaticBlock {

static{
    System.out.println("in static block");
}


{
    System.out.println("in initialization block");
}

public StaticBlock(){
    System.out.println("in const");
}

public static void main(String[] args) {
        System.out.println("in main method");
        StaticBlock block=new StaticBlock();
}

in static block
in main method
in initialization block
in const

Upvotes: 1

NAGHMAAN MOHASEEN
NAGHMAAN MOHASEEN

Reputation: 45

the explanation is quite in detail but iam abstracting it for this specific question first of all a class is loaded by the class loader subsystem when it refers to it for the first time in runtime and not compile time. so the ClassLoader itself is a class in java.lang package and

its instances are called as classLoader instances that load the classes now coming to details of this it follows an hierarchy with the BootStrap ClassLoader being at the top

note the BootStrap class loader itself is an instance of ClassLoader.

more ever these instances also perform verification ,preparing ,resolving symbolic references to keep it simple it performs dynamic linking of your java program.

now when your compiler compiles .java file it inserts a public static final field of type Class you can access it in your java.lang.Class obj=name_of_your_class.class

and it contains a method getClassLoader which tell the classLoader Instance that loaded this class.

fine its only by using this information the ClassLoaders get to know the name of the class to be loaded ie its fully qualified name(package.class)

now before searching for a file in its native file system and loading it it checks with its parent instance that it has already loaded that file nad this checking propagates all the way top BootclassLoader only if none of them have loaded it then only that instance loads that classfile . the details of how these things happen is irrelevant in this context.

and once the class is loaded the static block is executed in the initialization phase of class loader subsystem.

since i have already told that its the compiler that plays the role of inserting that field. and note that not finding main method is an runtime error so the compiler is not responsible for that rather it is the JVM .

from java 7 the main method is searched before and if we dont have we get this error in runtime but in java 6 and earlier version when class loading had taken place there itself the static block was exectued and then it searched to find the main method but if we provide System.exit(0) ; in the block it terminates the program even before search is made hence we did not have any error

although in java 7 probing for the main method is done before execution of the static block the execution of static block itself depends on the successful finding of main method.even though the order of execution of program is program is same as in java 6 and earlier edition.

further in detail the first element to be placed on the stack itself should be the main thread. and we know how the execution control flows and its even important to note that static blocks even if they are containing variable local to their block they are never placed as an activation record on the stack but rather on the method area. so from java 7 the JVM checks for the existence of main thread record on the stack then giving the control to the static blocks after which it executes all the static blocks in its order . whereas it did the reverse in java 6 and earlier edition

its also important to note we cannot nest a static block within any static or non static scope as this block has its only higher enclosed scope to be that of the class

i even know its a bit tricky to understand it but reading this answer will definitely provide a good ,accurate and deep understanding of static blocks .

Upvotes: -2

user176326
user176326

Reputation: 9

The most voted answer is 'mostly' correct, but not entirely. Consider the following code below where the class has a main method and a static method. The static method WILL execute (successfully) BEFORE the main method and constructor and produces the sequence: A B C D - which is not as you might have thought.

public class Sequence {
    Sequence() {
        System.out.print("c ");
    }
    {
        System.out.print("B ");
    }
    public static void main(String[] args) {
        new Sequence().go();
    }
    void go() {
        System.out.print("D ");
    }
    static{
        System.out.print("A ");
    }
}

Upvotes: 0

arshajii
arshajii

Reputation: 129537

If you put a System.exit(0) at the end of the static-block, it will run with no errors in Java 6 and below (without a valid main!). This is because the static block is executed before a valid main method is searched for, so if you exit the program at the end of the static block, you will receive no errors.

However, this behavior was changed in Java 7; now you must include an explicit main, even if it might never be reached.

In Java 7, the answer to the question is false, but in Java 6 and below the answer is indeed true.


public class Test {
    static {
        System.out.println("Hello World");
        System.exit(0);
    }
}

Java 6:

Hello World

Java 7:

Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)

Upvotes: 36

Mike Samuel
Mike Samuel

Reputation: 120546

Static blocks execute when a class is initialized. Normally, the main class will cause initialization of the bootstrap class, but there are other ways to bootstrap a program, for example via a VM's native embedding API.

Invoking the static main method of a class causes its initialization, but so do many other things:

  1. creating an instance of that class,
  2. calling any other static method,
  3. reading a static field (that is not final or has type other than a primitive type or String).

For more detail see the JLS chapter 12.4

The below shows this in action

public class Foo {
  static { System.out.println("Foo initialized"); }

  public static void main(String... argv) {
    Initialized.callingThisCausesClassInitialization();
  }

  static class Initialized {
    static { System.out.println("Initialized initialized"); }
    static void callingThisCausesClassInitialization() {}
  }

  static class NotInitialized {
    static { System.out.println("NotInitialized initialized"); }
    static void callingThisCausesClassInitialization() {}
  }
}

Running foo will print

Foo initialized
Initialized initialized

It will not print

NotInitialized initialized

because nothing is done during the execution of that program that causes its initialization.

It looks like your class has that behavior because it is never used, like NotInitialized above.

Upvotes: 7

Related Questions