LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 16

Identity of objects in a loop Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following Java program?

Main.java
class Ticket {
    static int created = 0;
    final int no;
    Ticket() { no = ++created; }
}

public class Main {
    public static void main(String[] args) {
        Ticket last = null;
        int same = 0;
        for (int i = 0; i < 5; i++) {
            Ticket t = new Ticket();
            if (t == last) same++;
            last = t;
        }
        System.out.println(Ticket.created + " " + last.no + " " + same);
    }
}
  • A 5 5 0 Correct
  • B 5 1 4
  • C 1 1 4
  • D 5 5 4
Correct Answer: Option A

new always creates a distinct object, so no two tickets are ==.

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