LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 6

A method changing an object it receives Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following Java program?

Main.java
class Wallet { int money = 100; }

public class Main {
    static void spend(Wallet w, int amount) { w.money -= amount; }
    static void replace(Wallet w) { w = new Wallet(); w.money = 999; }

    public static void main(String[] args) {
        Wallet w = new Wallet();
        spend(w, 30);
        replace(w);
        spend(w, 20);
        System.out.println(w.money);
    }
}
  • A 50 Correct
  • B 999
  • C 100
  • D 979
Correct Answer: Option A

spend changes the caller's object; replace only re-points its own parameter.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links