A static field shared by every object — Aptitude Question
A static field shared by every object: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
What does this Java program print?
public class Main {
static int count = 0;
int id;
Main() {
count++;
id = count;
}
public static void main(String[] args) {
Main p = new Main();
Main q = new Main();
Main r = new Main();
System.out.println(p.id + " " + r.id + " " + Main.count);
}
}Options
- 1 1 1
- 1 3 1
- 1 3 3
- 3 3 3
Show the answer and the worked solution
Correct answer: C. 1 3 3
Worked solution
- There is a single count shared by every object, and each constructor call raises it: after three objects it is 3.
- Each object has its own id, fixed at construction time, so p.id = 1, q.id = 2 and r.id = 3.
- The program prints p.id, r.id and count, that is 1 3 3.
Answer: 1 3 3.
The idea
A static field exists once per class, an instance field once per object. Reading a snapshot of the static into an instance field is the standard way to number objects as they are created.
Shortcut. Main.count is shared and ends at 3 after three constructions, ruling out "1 1 1" and "1 3 1"; p.id was fixed at 1 when p was made.
Common trap. "3 3 3" treats id as a live view of count; each constructor copies the current count into id, so p keeps its snapshot of 1.
All Programming Fundamentals questions · placement mock tests