LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 2

Two variables referring to one object Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Box { int size; }

public class Main {
    public static void main(String[] args) {
        Box a = new Box();
        a.size = 5;
        Box b = a;
        b.size = 9;
        a = new Box();
        a.size = 1;
        System.out.println(a.size + " " + b.size);
    }
}
  • A 1 9 Correct
  • B 9 9
  • C 1 1
  • D 5 9
Correct Answer: Option A

b changes the original object; then a is pointed at a new object, while b keeps the original.

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