What is the difference b/w static block and constructor

The static block will be executed when the class is loaded on to the JVM. It is executed only once.
Constructor will be executed while creating the object. The constructor is called only once for an object and it is called as many times as you create the object.
Ex: if a class Test is having one static block and a constructor. Then the static block is executed only once. If you create three objects based on Test class then the constructor is called three times.
Static blocks are executed before running the main method. where as constructor are called while creating an object of an class..

Public Class test{
if we above run the above program it will print welcome.

No comments:

Post a Comment