Java quiz 44: How static blocks work?

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
Select    31   32   33   34   35   36   37   38   39   40   41   42   43   44   By title 
>

Here is a simpler version of static blocks, I think that this one will give you an idea how static blocks work in Java.

Java quiz 44: How static blocks work?

Level: Easy

What happens if the following code is compiled and run?

public class MyClass
{
  static
  {
    calculate(4);
  }
  
  static void calculate(int nr)
  {
    int total = nr * 3;
    System.out.print(total);
  }
  public static void main(String[] args)
  {
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “0” to the standard output.
b. This program writes “4” to the standard output.
c. This program writes Nothig to the standard output.
d. This program writes “3” to the standard output.
e. This program writes “total” to the standard output.
f. This program writes “12” to the standard output.
g. You cannot run this code because the main block is empty.

Answer explanation

  1. The static block is executed even if the body of the main mehod is empty.
  2. The statement calculate(4); within the static block invokes the method calculate().
  3. The method calculate(), calculates the product of the parameter multiply by 3 which is 4 * 3 = 12.
  4. The statement System.out.print(total); writes 12 to the standard output.

The correct answer is: f.




Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *