Java OCA OCP Practice Question 2656

Question

Consider the following program and choose the correct option that describes its output:

import java.util.concurrent.atomic.AtomicInteger;

class Main {/*from w w  w  .j a v  a2s  .co m*/
        public static void main(String []args) {
                AtomicInteger i = new AtomicInteger(0);
                increment(i);
                System.out.println(i);
        }
        static void increment(AtomicInteger atomicInt){
                atomicInt.incrementAndGet();
        }
}
  • a) 0
  • b) 1
  • c) This program throws an UnsafeIncrementException.
  • d) This program throws a NonThreadContextException.


b)

Note

Though the return value in the call atomicInt.incrementAndGet(); is ignored,

the method mutates the integer value passed through the reference variable atomicInt,

so the changed value is printed in the main() method.

Note that AtomicInteger can be used in thread or non-thread context.




PreviousNext

Related