Question 16
Back to Exercise
What is the output of the following Java program?
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!