Is it possible to print message on console without main and static block in java?

You could define a custom class loader that prints your message :

public class MyClassLoader extends ClassLoader {
    public MyClassLoader(ClassLoader other) {
         super(other);
         System.out.println("Hi there");
         System.exit(0);
    }
}

Then run the java command :

java -Djava.system.class.loader=MyClassLoader

(don't need to add a class as parameter)


I have asked this question:Without using static and main how could we print
message on console?Is it possible?

Answer is No!

You cannot execute anything unless main() method is called. Prior to Java 7 classes were loaded before main() method was looked up. So you could print your data through static blocks(static block gets executed when classes are loaded) but from java 7 onward even that is not possible. So you always have to execute the main() method first.

Even in frameworks like Spring beans are generally initialized only when it's context is referenced(again main() is required to be executed first).So there is no way you can print something to console without invoking main() method or through static functions/blocks.

Tags:

Java