AtomicInteger
represents an int value that may be updated AtomicInteger
is present in the java.util.concurrent.atomic
package.
The incrementAndGet
method of the AtomicInteger
will atomically increment the current value by 1 and returns the updated value of the AtomicInteger
object.
public final int incrementAndGet()
This method doesn’t take any argument.
This method returns the incremented value as an integer.
The code below demonstrates how to use the incrementAndGet
method:
import java.util.concurrent.atomic.AtomicInteger;class IncrementAndGet{public static void main(String[] args) {AtomicInteger atomicInteger = new AtomicInteger(10);System.out.println("The value in the atomicInteger object is " + atomicInteger.get());System.out.println("\nCalling atomicInteger.incrementAndGet()");int val = atomicInteger.incrementAndGet();System.out.println("The new Value is : " + val);}}
Line 1: We have imported the AtomicInteger
class.
Line 2: Definition of class IncrementAndGet
that shows the implementation of incrementAndGet
method.
Line 4: Created a new object for the AtomicInteger
class with the name atomicInteger
and with the value 10
.
Line 9: Called the incrementAndGet
method. This method will increment the current value(10
) by 1
and returns the new value(11
).