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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:
java ,objects ,methods ,quiz

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}