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

Java Quiz: Nested Classes and Constructors

DZone's Guide to

Java Quiz: Nested Classes and Constructors

DZone's latest quiz for intermediate Java developers! Learn how nested classes and constructors behave.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Purpose

This is a quiz aimed at intermediate developers to:

  1. Introduce you to how nested classes behave in Java.

  2. Improve your internal calculations and expectations regarding nested classes and constructors.

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

public class Outer{

    private int x;
    private int y;

    Outer(){
        x = 4;
        y = 3;
    }
    Outer(int z){
        new Outer();
        x += z;
        y -= z;
    }
    class Inner{

        Inner(){
            x ++ ;
            y += 2;
        }
        Inner(int i){
            this();
            x -= i;
            y += i;
            System.out.print(x ++ + " " + -- y + " ");
        }
    }
    public static void main(String[] args){
        Inner inner = new Outer(3).new Inner(2);
    }
}

Answer Explanation

First, create the object Inner:

Inner inner = new Outer(3).new Inner(2);
new Outer(3) calls the int-arg constructor of the outer class

new Outer(); // this new object doesn't affect the initial value of x & y.
x += z; // z = 3. x = 0 + 3 = 3.
y -= z; // y = 0 – 3 = -3

Now Inner(2) calls the int-arg constructor of the Inner class. 

Inner(int i){
this(); // this line calls the no-arg constructor of the inner class
x++; // x = 3 + 1 = 4
y+=2; // y = -3 + 2 = -1

Parameter i = 2;
x -= i; // x = 4 – 2 = 2
y += i; // y = -1 + 2 = 1
System.out.print(x ++ + " " + -- y + " ");

x++ actually means x = x + 1; and adds one to the value after the expression is evaluated. --y is the predecrement and x++ is the postincrement. x is still 2, and --y decrements by one, so y = 1 - 1 = 0. So "2 0" is written to the standard output, making B is the correct answer. 

You can learn more about Sar here at his website! Hope you enjoyed this quiz. Let us know your thoughts in the comments!

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,constructors ,classes ,nested class

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}