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

Java Quiz: Passing Objects to Methods

DZone's Guide to

Java Quiz: Passing Objects to Methods

The latest intermediate-level Java quiz from DZone's resident quizmaster Sar Maroof!

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Before we get on with this week's quiz, we'd like to let you know that Sar's Java quizzes will be every other week starting with this one. Let's get started!

Passing Objects to Methods

public class MyClass{

    int x;

    MyClass(int y){
        this.x = y ++ ;
    }
    int method(MyClass mc){
        if(mc.x == 5){
            mc.x += 6;
            method(mc);
        }
        if(mc.x == 6){
            mc.x += 9;
            method(mc);
        }
        return ++ mc.x;
    }
    public static void main(String[] args){
        MyClass mc = new MyClass(5);
        System.out.println(mc.method(mc));
    }
}


Purpose

  1. Introduce a new trick when using Java

  2. Brain training to test your expectations

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


Solution

MyClass mc = new MyClass(5);

By Creating the “mc” object, we call the MyClass int-arg constructor.

For this.x = y++; , the value of x remains “5”. y++ increments “1” after the expression is evaluated. When we pass “5” to the method, the condition if(mc.x == 5) is true.

mc.x += 6 adds 6 to the value of x, so that x = 5 + 6 = 11. return ++ mc.x then adds “1” to the value of x: x = 11 + 1 = 12.

By invoking the method(mc), both conditions “if(mc.x == 5)” and “if(mc.x == 6)” are false.

return ++ mc.x; adds “1” to the value of x, so the correct answer is: x = 12 + 1 = 13.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
java ,objects ,methods ,quiz

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}