Java OCA OCP Practice Question 2277

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;
     }/*from  w w w.  j av a  2s .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, the assert fails and the program results in an AssertionError.




PreviousNext

Related