What is the AtomicInteger.incrementAndGet method in Java?

AtomicInteger represents an int value that may be updated atomicallyAtomic operation is performing a single unit of work on a resource. During that operation, no other operations are allowed on the same resource until the performing operation is finished.. The 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.

Syntax

public final int incrementAndGet()

Parameters

This method doesn’t take any argument.

Return value

This method returns the incremented value as an integer.

Code

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);
}
}

Explanation

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).

Free Resources