Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Quiz 2: Comparing Class Variables With Instance Variables

DZone's Guide to

Java Quiz 2: Comparing Class Variables With Instance Variables

Stop by for the answer to the first Java quiz in this series as well as a new challenge—this time involving the differences between class and instance variables.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Before we dive into this week's quiz, here is the answer to Quiz 1: Overriding Methods.

  1. By creating the object of MySub, the constructor of the superclass MySuper is called.

  2. The constructor of MySuper invokes the method myMethod.

  3. The method myMethod is overridden in the subclass MySub.

  4. The method myMethod writes the value of str2 to the standard output.

  5. The constructor of the superclass tries to access the variable str2 inside its subclass before it is initialized.
    Therefore the program writes null instead of "y" to the standard output.
    If you have any other explanation or opinion, share it please in the comments!

Here is today's quiz!

What is written to the standard output as the result of executing the following code?

public class MyClass {  
    static int x;  
    String s = "";  
    static String s2 = "";   
    public MyClass(int  i) {    
        x += i;    
        s += x;    
        s2 += x;  
    }  
    public static void main(String[] args) {    
        new MyClass(2);    
        MyClass mc = new MyClass(1);    
        new MyClass(4);    
        System.out.print(mc.s + mc.s2);  
    }
}



Select the correct answer.

  • A. This code writes "1137" to the standard output.

  • B. This code writes "3237" to the standard output.

  • C. This code writes "35" to the standard output.

  • D. This code writes "312" to the standard output.

  • E. This code writes "323" to the standard output.

The correct answer and its explanation will be included in the next quiz in two weeks! For more Java quizzes, puzzles, and assignments, take a look at my site!

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java ,class variables ,instance variables ,quiz

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}