Question discussion

What is the output of the following Java program?class Counter { static int n; int id; Counter() { id = ++n; } } public class Main { public…

1570Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

class Counter {
    static int n;
    int id;
    Counter() { id = ++n; }
}
public class Main {
    public static void main(String[] args) {
        new Counter(); new Counter();
        Counter c = new Counter();
        System.out.println(c.id + " " + Counter.n);
    }
}
  • A1 3
  • B3 1
  • C3 3
  • D0 3
Correct answer: C

Explanation

The static counter n is shared by all objects and reaches 3; the third object takes id = 3.

Discussion 0

Nobody has replied yet. Start the discussion!