LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Find the Error · Question 6

Error: using ++ on an AtomicInteger Answer, explanation & discussion

  • Find the error
  • Easy
  • 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
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        AtomicInteger hits = new AtomicInteger();
        hits++;
        System.out.println(hits);
    }
}
  • A AtomicInteger needs an initial value
  • B AtomicInteger is an object, not a number – operators like ++ do not apply; call hits.incrementAndGet() Correct
  • C hits must be volatile
  • D println cannot print atomics
Correct Answer: Option B

javac: "bad operand type AtomicInteger for unary operator '++'".

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