Java quiz 30: Static, instance statements and blocks

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes    Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

Have you ever though which block, constructor or statement is called first when you compile and run your code? This quiz demonstrates that idea!

Java quiz 30: Static, instane statements and blocks

Level: Normal

What is the output of the following code?

public class Car
{
  Car()
  {
    System.out.print("Toyota");
  }
  
  static String brand1 = getBrand("BMW ");
  String brand2 = getBrand("Volvo ");
  static
  {
    System.out.print("Porshe ");
  }
  
  public static String getBrand(String brand)
  {
    System.out.print(brand);
    return brand;
  }
  public static void main(String[] args)
  {
    Car car = new Car();
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “Toyota” to the standard output.
b. This program writes “Toyota BMW Porshe” to the standard output.
c. This program writes “Toyota BMW Volvo Porshe” to the standard output.
d. This program writes “BMW Porshe Volvo Toyota” to the standard output.
e. This program writes “Porshe Toyota” to the standard output.
f. Runtime exception.
g. This code fails to compile.

Answer explanation

  1. First of all, static statements and blocks are called in the order of their definition.
  2. Instance statements and blocks are called in the order of their definition.
  3. Finally, the constructor is called.

The correct answer is: d.





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 *