Number数据类型不会溢出

Number数据类型不会溢出

本文介绍了为什么Java Number数据类型不会溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java数字/数字数据类型(例如(Integer/Long/...))不会引发溢出异常?例如:对于

Why java Number / Numeric datatypes such as (Integer/Long/...) doesnt throw overflow exception?For example: We get mathematically wrong answer for following

Integer val = Integer.MAX_VALUE * 2;
System.out.println("Max val unexpected" + val);

**最大val意外2-**

** Max val unexpected-2**

我知道;这些数据类型的核心使用原始的Java数据类型.仍然,通过抛出诸如..ValueOverflowException之类的东西来防止错误答案并不是一个好主意.想扩展并添加这种行为,但是所有这些类都是最终的.

I know; at the core these datatypes use primitive java datatypes.Still , isn't a good idea to prevent wrong answer by throwing something like..ValueOverflowException.Thought of extending and adding this behaviour but these all classes are final..

请发表您的想法和看法.意见.

Please post your thoughts & opinions.

推荐答案

这些类型只是原始类型的包装,因此,如果它们的行为不同,这将是意外的.这些类型不引发这些异常的原因之一是,如果执行了此类检查,则代价将非常高,而且处理器上的这些整数类型在溢出时不会触发中断(而相反,浮点类型可以触发中断)对于各种事件).如果您希望支持任意精度,那么您可能会对BigInteger类型感兴趣.

Those types are just wrappers for the primitive types, and so it would be unexpected if they behaved differently. One reason those types do not throw those exceptions is that it would be incredibly costly if such checks were performed, and these integral types on the processor don't trigger interrupts when they overflow (whereas, by contrast, the floating point types can trigger interrupts for various events). If you are looking to support arbitrary precision, then you might be interested in the BigInteger type.

这篇关于为什么Java Number数据类型不会溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:35