Java - Interview Questions and Answers on Static Block

Q1.  How can we run a java program without making any object?

Ans. By putting code within either static method or static block.

Q2.  Explain static blocks in Java ?

Ans. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {
    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

Q3.  How can we create objects if we make the constructor private ?

Ans. We can do so through a static public member method or static block.

Q4.  Is it possible to compile and run a Java program without writing main( ) method?

Ans. Yes, it is possible by using a static block in the Java program.

Q5.  Similarity and Difference between static block and static method ?

Ans. Both belong to the class as a whole and not to the individual objects. Static methods are explicitly called for execution whereas Static block gets executed when the Class gets loaded by the JVM.

Q6.  Will the static block be executed in the following code ? Why ?

class Test
{
    static
    {
          System.out.println("Why I am not executing ");
    }
    public static final int param=20;
}

public class Demo 
{
    public static void main(String[] args) 
    {
        System.out.println(Test.param);
    }
}

Ans. No the static block won't get executed as the referenced variable in the Test class is final. Compiler replaces the content of the final variable within Demo.main method and hence actually no reference to  Test class is made.

Q7.  Will static block for Test Class execute in the following code ? 

class Test
{
  static
  {
     System.out.println("Executing Static Block.");
   }
   public final int param=20;
   
   public int getParam(){
  return param; 
   }
}

public class Demo 
{
   public static void main(String[] args) 
   {
      System.out.println(new Test().param);
    }
}


Ans. Yes.