LearnFrenzy
Sign in Take a free test

Classes and Objects · Find the Error · Question 7

Error: using a local reference that was never assigned Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links