Related Articles

Related Articles

AtomicInteger updateAndGet() method in Java with Examples
  • Last Updated : 17 Jun, 2019

The Java.AtomicInteger.updateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value. It takes an object of IntUnaryOperator interface as its parameter and applies the operation specified in the object to the current value. It returns the updated value.

Syntax:

public final int updateAndGet(IntUnaryOperator function)

Parameters: This method accepts as parameter an IntUnaryOperator function.
It applies the given function to the current value of the object.

Return Value: The function returns the updated value of the current object.

Example to demonstrate the function.



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate the above function
  
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;
  
public class Demo {
    public static void main(String[] args)
    {
  
        // Atomic Integer initialized with a value of 10
        AtomicInteger ai = new AtomicInteger(10);
  
        // Unary operator defined to negate the value
        IntUnaryOperator unaryOperator = (x) -> - x;
  
        System.out.println("Initial Value is " + ai);
  
        // Function called and the unary operator
        // is passed as an argument
        int x = ai.updateAndGet(unaryOperator);
        System.out.println("Updated value is " + x);
    }
}

chevron_right


Output:

Initial Value is 10
Updated value is -10

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :