Trace Java Static and Instance Field Initialization
Company: Pinduoduo
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
# Trace Java Static and Instance Field Initialization
Consider a Java class with static fields `a` and `c`, an instance field `b`, and this initialization: `c = 2`; the constructor executes `a++`, `b++`, and `c++`. All other numeric fields use Java's default initialization. After `Test test = new Test();`, what do `System.out.println(a)`, `System.out.println(test.b)`, and `System.out.println(c)` print? Explain class initialization, object initialization, and what changes after constructing a second instance.
### Constraints & Assumptions
- The program starts in a fresh JVM and no other `Test` object exists.
- The fields are `int`; the constructor contains only the three increments.
### Clarifying Questions to Ask
- Is `b` an instance field while `a` and `c` are static?
- Should the answer include a second construction to expose shared state?
```hint Separate class state from object state
Write the default value and initializer value before applying constructor increments.
```
### What a Strong Answer Covers
- Exact output after one construction and after a second construction.
- Default initialization and the order of field initialization versus constructor execution.
- Why static state is shared while each object has its own `b`.
### Follow-up Questions
- What changes if `b` is also declared `static`?
- Is accessing `a` through an instance legal, and why is it discouraged?
Quick Answer: Consider a Java class with static fields `a` and `c`, an instance field `b`, and this initialization: `c = 2`; the constructor executes `a++`, `b++`, and `c++`. Make the API or object boundaries explicit, then cover invariants, edge cases, testing strategy, and operational trade-offs.