Over a million developers have joined DZone.

Java Quiz: Passing Objects to Methods

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

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

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 }}