Java · Question 27 · Hard

What will be the output of the following Java program?

class Counter {
    static int s = 0;
    int i = 0;

    Counter() {
        s++;
        i++;
    }
}

public class Main {
    public static void main(String[] args) {
        new Counter();
        new Counter();
        Counter c = new Counter();
        System.out.println(c.s + " " + c.i);
    }
}
  1. 1 1
  2. 1 3
  3. 3 1
  4. 3 3
Answer and explanation

Answer: C. 3 1

Explanation: s is static, so all three objects share one copy and it reaches 3. i is an instance field, so each object has its own copy, and c's copy is 1.

Previous: What will be the output of the following Java program? · Next: What will be the output of the following Java program?

Practise java

Try a fresh set of java questions with an explanation after every answer, free and without signing up: Java practice. Or sit a full placement mock test.

More java questions

More technical & programming practice

Python · Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge