Java quiz 30: Static, instance statements and blocks

<< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
 Q25   Q26   Q27   Q28   Q29   Q30   Q31   Q32   Q33   Q34   Q35   Q36 
 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.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.




Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           

 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 *

Sarmaroof © 2017