increment java_Java Math incrementExact()用法及代码示例

incrementExact()是Java中的内置函数,该函数返回以1递增的参数,如果结果溢出指定的数据类型long或int(取决于方法参数使用的是哪种数据类型),则会引发异常。

用法:

int incrementExact(int num)

long incrementExact(long num)

参数:该函数接受一个强制参数,如上所示和以下内容:

num -该参数指定必须增加的数字。

返回值:函数返回的参数加1,如果结果溢出指定的数据类型为long或int,则抛出异常,具体取决于方法参数上使用的是哪种数据类型。

例子:

Input:12

Output:13

Input:-3

Output:-2

程序1:演示功能工作的程序

// 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 y = 12;

System.out.println(Math.incrementExact(y));

int x = -3;

System.out.println(Math.incrementExact(x));

}

}

输出:

13

-2

程序2:演示函数溢出的程序

// Java program to demonstrate overflow

// of java.lang.Math.incrementExact() method

import java.lang.Math;

class Gfg1 {

// driver code

public static void main(String args[])

{

int y = Integer.MAX_VALUE;

System.out.println(Math.incrementExact(y));

}

}

输出:

Exception in thread "main" java.lang.ArithmeticException:integer overflow

at java.lang.Math.incrementExact(Math.java:909)

at Gfg1.main(File.java:12)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值