Java OCA OCP Practice Question 3220

Question

Consider the following program:

import java.util.concurrent.atomic.*;

public class Main {
     static AtomicInteger ai = new AtomicInteger(10);
     public static void check() {
             assert (ai.intValue() % 2) == 0;
     }// www. j av  a2s. c  o  m
     public static void increment() {
             ai.incrementAndGet();
     }
     public static void decrement() {
             ai.getAndDecrement();
     }
     public static void compare() {
             ai.compareAndSet(10, 11);
     }
     public static void main(String []args) {
             increment();
             decrement();
             compare();
             check();
             System.out.println(ai);
     }

}

The program is invoked as follows:

java -ea Main

What is the expected output of this program?

  • A. It prints 11.
  • B. It prints 10.
  • C. It prints 9.
  • D. It crashes throwing an AssertionError.


D.

Note

The initial value of AtomicInteger is 10.

Its value is incremented by 1 after calling incrementAndGet().

After that, its value is decremented by 1 after calling getAndDecrement().

The method compareAndSet(10,11) checks if the current value is 10, and if so sets the atomic integer variable to value 11.

Since the assert statement checks if the atomic integer value % 2 is zero (that is, checks if it is an even number), the assert fails and the program results in an AssertionError.




PreviousNext

Related