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

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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!

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
java ,constructors ,classes ,nested class

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}