Hello, a world without a basic method (Horstmann)

Horstmann in Core Java 7th Edition writes that you can show Hello, world without a main method. This is done as follows:

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

He says that first of all, Hello, the 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 can’t model it. Is it already fixed?

+4
source share
2 answers

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

So, if you run your code on any version prior to java 7, you will see that the static block is executing.

The book you are reading cannot be written for java 7, but the jdk & jre that you use to execute the samples is version 7.

Tip . As a good reading practice, you should try to run sample books in the same version that are listed in the book to avoid confusion. Although in this case, your confusion will force you to learn something new about java 7.

+6
source

Prior to Java 7, the JVM is used to load a class before searching for the main () method.

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

So, when you do this using java Hello , the class will be loaded first and Hello, world will be printed (static methods / block are executed when classes are loaded, and classes are loaded when they are referenced). Then the JVM will look for the main () method in the Hello class and will raise an error as it is not. However, this is fixed in java 7. Therefore, if you use java 7, you will immediately get an error.

+2
source

Source: https://habr.com/ru/post/1497562/


All Articles