Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hello, world without main method (by Horstmann)

Tags:

java

Horstmann in Core Java 7th edition writes that it is possible to show Hello, world without main method. It is done like this:

public class Hello{
    static{
        System.out.println("Hello, world");
    }
}

He says that first of all Hello, world will be written. And only then you will receive an error message.

I use

java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

And I fail to model this. Has it already been fixed?

like image 570
Kifsif Avatar asked Feb 15 '23 13:02

Kifsif


1 Answers

Java 7 looks for a main method before loading the class. This is a behavior change from previous java versions and hence your static block is not executing. In previous versions, the behavior was that JRE used to look for main method post loading the class and after executing the static blocks.

So if you run your code on any version prior to java 7 you will see that static block executes.

The book you are reading may not be written for java 7 but the jdk& jre you are using to execute the samples is version 7.

An advice : As a good reading practice you should try to run the book samples on the same version as specified in the book to avoid confusion. Although in this instance, your confusion lead you to learn something new about java 7.

like image 158
Juned Ahsan Avatar answered Feb 20 '23 09:02

Juned Ahsan