Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIJava Math incrementExact(int x) method

Java Math incrementExact(int x) method

The java.lang.Math.incrementExact() is a built-in math function in java which returns the argument incremented by one.It throws an exception if the result overflows an int.As incrementExact(int x) is static, so object creation is not required.

Syntax :

public static int incrementExact(int x)
Parameter :
x : the value to be incremented
Return :
This method returns the argument incremented by one.
Exception :
It throws ArithmeticException - if the result overflows an int

Example : To show working of java.lang.Math.incrementExact() method.




// Java program to demonstrate working
// of java.lang.Math.incrementExact() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
        int a = 0;
  
        for (int i = 0; i < 5; i++) {
            a = Math.incrementExact(a);
            System.out.println(a);
        }
    }
}


Output:

1
2
3
4
5




// Java program to demonstrate working
// of java.lang.Math.incrementExact() method
import java.lang.Math;
  
class Gfg2 {
  
    // driver code
    public static void main(String args[])
    {
        int x = Integer.MAX_VALUE;
  
        System.out.println(Math.incrementExact(x));
    }
}


Output:

Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.lang.Math.incrementExact(Math.java:909)
    at Gfg2.main(File.java:13)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments