How to Print Welcome Message Before Main Method is Executed in Java

If you want to print a welcome message before the main method is executed in Java, a static block is the best place to do that. What is a static block? A static block is nothing but a code block just like instance block. The static block does not depend on any object. What that means is, even though you make mulitple instances of a class, the static block will be executed only once.

Java executes static blocks only once, even before the main method is executed. Let’s look at this in below example.

Example

package com.techstackjournal;

public class StaticBlock {
	
	static {
		System.out.println("Welcome!!!");
	}

	static {
		System.out.println("We wish you the best!!!");
	}

	public static void main(String[] args) {
		System.out.println("Hello World!!!");
	}

}

Output:

Welcome!!!
We wish you the best!!!
Hello World!!!

When Java runs this program, first it looks into the class which is being executed for the presence of static block and executes them. Then it looks into all the classes of the objects instantiated within that class and executes respective static blocks of those classes as per their availability. Then it will proceed with execution of instance blocks and constructor.

In this above program, Java first executes the static blocks in which main method is present. Since we’ve two static blocks it will first execute the first one before it proceeds to execute the next one.

See also  How to convert byte array to String