LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Find the Error · Question 6

Error: a static local variable Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

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

Main.java
public class Main {
    static int nextId() {
        static int counter = 0;
        return ++counter;
    }

    public static void main(String[] args) {
        System.out.println(nextId() + nextId());
    }
}
  • A counter must be long
  • B Java has no static local variables (unlike C); declare counter as a static field of the class Correct
  • C nextId cannot be static
  • D ++counter must be counter++
Correct Answer: Option B

Local variables live in the stack frame and always disappear when the method returns.

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