Question 7
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
class Timer {
int seconds;
void tick() { seconds++; }
}
public class Main {
public static void main(String[] args) {
Timer t;
t.tick();
System.out.println(t.seconds);
}
}
- A tick must be static
- B t is a local variable that was never assigned – no object was created; write Timer t = new Timer(); Correct
- C seconds must be initialised
- D Timer must be public
Correct Answer: Option B
For local variables javac catches this at compile time ("might not have been initialized"); a null field would fail at run time instead.
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!