Java quiz 30: Static, instance statements and blocks

<< Java Quizzes    Green = Easy,  Blue = Normal,  Red = Hard
 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   31   32   33   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". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer 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 *