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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,objects ,methods ,quiz

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}