Java quiz 43: Statitc blocks and constructors

  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 
>

Calling static blocks and constructors.

Java quiz 43: Static blocks and constructors

Level: Hard

What is the output of the following code?

public class MyClass
{
  static int nr1 = 5;
  int nr = getNumber(2);
  
  MyClass()
  {
    nr = getNumber(3);
  }
  static
  {
    nr1--;
  }
  public int getNumber(int nr)
  {
    nr1 += nr;
    System.out.print(nr1);
    return nr;
  }
  public static void main(String[] args)
  {
    MyClass mc = new MyClass();
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “0” to the standard output.
b. This program writes “69” to the standard output.
c. This program writes “8” to the standard output.
d. This program writes “5” to the standard output.
e. This program writes nothing to the standard output.
f. Runtime exception.
g. This code fails to compile.

Answer explanation

  1. The static statements and blocks are called in order of their definition. n1 = 5 and n1–; decreases the value of n1 by one. So, n1 = 4.
  2. The instance statements and blocks are called in order of their definition. So, the statement int nr = getNumber(2); is executed and The statement nr1 += nr; increases the value of nr1 by 2. So, nr1 = 6. The statement System.out.print(nr1); writes “6” to the standard output.
  3. The constructor is called finally. So, the statement nr = getNumber(3);
    Increases the value of nr1 by 3. See the method. So, nr1 = 9.
    The statement System.out.print(nr1); writes “9” to the standard output.

The correct answer is: b.




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 *