English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java Other Topics

Java Math incrementExact() Usage and Example

Java Math Mathematical Methods

Java Math incrementExact() adds the specified number1and returns.

The syntax of the incrementExact() method is:

Math.incrementExact(num)

Note: incrementExact() is a static method. Therefore, we can use the Math class name to access this method.

crementExact() parameter

  • num - to add1of the parameter

Note: The parameter's data type should be int or long.

IncrementExact() returns value

  • Add the parameter1Returns the value after

Example1: Java Math.incrementExact()

class Main {
  public static void main(String[] args) {
    //Create a int variable
    int a = 65;
    //incrementExact() with int parameter
    System.out.println(Math.incrementExact(a));  // 66
    //Create a long variable
    long b = 52336L;
    //incrementExact() with long parameter
    System.out.println(Math.incrementExact(b));  // 52337
  }
}

In the above example, we used the Math.incrementExact() method with int and long variables to1Add to each variable.

Example2: Math.incrementExact() throws an exception

If the result of the addition overflows the data type, the incrementExact() method will throw an exception. That is, the result should be within the range of the specified variable's data type.

class Main {
  public static void main(String[] args) {
    //Create an int variable.
    //maximum int value
    int a = 2147483647;
    //incrementExact() with int parameter.
    //throw an exception
    System.out.println(Math.incrementExact(a));
  }
}

In the above example, the value of a is the maximum value of int. Here, the incrementExact() method will1Add to a.

   a + 1  
=> 2147483647 + 1
=> 2147483648    // Out of the range of the int type

Therefore, the incrementExact() method causes an exception out of the range of the int type.

Recommended Tutorials

Java Math Mathematical Methods