Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Number in java

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains how to use Number in java. Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "How to use Number in java"!

profile

In java, we can call numbers byte, short, int, long, float, double and char. What do we need to pay attention to when using these nubmers? Let's take a look.

Range of Number

Each Number type has its scope. Let's look at the scope of Number type in java:

Considering our most common int operation, although int's range is large enough, if we do some int operations, we may still exceed int's range.

What does it send beyond int? Consider the following example:

public void testIntegerOverflow(){ System.out.println(Integer.MAX_VALUE+1000); }

Run results: -2147482649.

Obviously Integer.MAX_VALUE+1000 will exceed the maximum value range of Integer, but instead of getting an exception, we get an incorrect result.

The correct action is to throw an exception if we encounter an Overflow problem: ArithmeticException.

How to prevent this kind of IntegerOverflow problem? Generally speaking, we have the following ways.

The first way: before doing Integer operation, pre-determine whether it is out of range:

For example:

static final int safeAdd(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE - right : left

< Integer.MIN_VALUE - right) { throw new ArithmeticException("Integer overflow"); } return left + right; } 上面的例子中,我们需要进行两个整数相加操作,在相加之前,我们需要进行范围的判断,从而保证计算的安全性。 第二种方式:使用Math的addExact和multiplyExact方法: Math的addExact和multiplyExact方法已经提供了Overflow的判断,我们看下addExact的实现: public static int addExact(int x, int y) { int r = x + y; // HD 2-12 Overflow iff both arguments have the opposite sign of the result if (((x ^ r) & (y ^ r)) < 0) { throw new ArithmeticException("integer overflow"); } return r; } 看下怎么使用: public int addUseMath(int a, int b){ return Math.addExact(a,b); } 第三种方式:向上转型 既然超出了Integer的范围,那么我们可以用范围更大的long来存储数据。 public static long intRangeCheck(long value) { if ((value < Integer.MIN_VALUE) || (value >

Integer.MAX_VALUE)) { throw new ArithmeticException("Integer overflow"); } return value; } public int addUseUpcasting(int a, int b){ return (int)intRangeCheck((long)a+(long)b); }

上面的例子中,我们将a+b转换成了两个long相加,从而保证不溢出范围。

然后进行一次范围比较,从而判断相加之后的结果是否仍然在整数范围内。

第四种方式:使用BigInteger

我们可以使用BigInteger.valueOf(a)将int转换成为BigInteger,再进行后续操作:

public int useBigInteger(int a, int b){ return BigInteger.valueOf(a).add(BigInteger.valueOf(b)).intValue(); }区分位运算和算数运算

我们通常会对Integer进行位运算或者算数运算。虽然可以进行两种运算,但是最好不要将两种运算同时进行,这样会造成混淆。

比如下面的例子:

x += (x >>2); System.out.println(i>>2); System.out.println(i/4); }

本来我们想做的是将i除以4,结果发现只有最后一个才是我们要的结果。

我们来解释一下,第一个i>>>2是逻辑右移,将会把最左边的填充成0,所以得出的结果是一个正值1073741821。

第二个i>>2是算数右移,最左边的还是会填充成1,但是会向下取整,所以得出结果是-3.

直接使用i/4,我们是向上取整,所以得出结果是-2.

注意不要使用0作为除数

我们在使用变量作为除数的时候,一定要注意先判断是否为0.

兼容C++的无符号整数类型

在java中只有16位的char表示的是无符号整数,而int实际上表示的是带符号的整数。

而在C或者C++中是可以直接表示无符号的整数的,那么,如果我们有一个32位的无符号整数,该怎么用java来处理呢?

public int readIntWrong(DataInputStream is) throws IOException { return is.readInt(); }

看上面的例子,我们从Stream中读取一个int值,如果是一个32位的无符号整数,那么读出来int就变成了有符号的负整数,这和我们的期望是相符的。

考虑一下,long是64位的,我们是不是可以使用long来表示32位的无符号整数呢?

public long readIntRight(DataInputStream is) throws IOException{ return is.readInt() & 0xFFFFFFFFL; // Mask with 32 one-bits }

看上面的例子,我们返回的是long,如果将32位的int转换成为64位的long,会自动根据符号位进行补全。

所以这时候我们需要和0xFFFFFFFFL进行mask操作,将高32位重置为0.

NAN和INFINITY

在整型运算中,除数是不能为0的,否则直接运行异常。但是在浮点数运算中,引入了NAN和INFINITY的概念,我们来看一下Double和Float中的定义。

public static final double POSITIVE_INFINITY = 1.0 / 0.0;public static final double NEGATIVE_INFINITY = -1.0 / 0.0;public static final double NaN = 0.0d / 0.0;public static final float POSITIVE_INFINITY = 1.0f / 0.0f;public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;public static final float NaN = 0.0f / 0.0f;

1除以0就是INFINITY,而0除以0就是NaN。

接下来,我们看一下NAN和INFINITY的比较:

public void compareInfinity(){ System.out.println(Double.POSITIVE_INFINITY == Double.POSITIVE_INFINITY); }

运行结果是true。

public void compareNaN(){ System.out.println(Double.NaN == Double.NaN); }

运行结果是false。

可以看到NaN和NaN相比是false。

那么我们怎么比较NaN呢?

别急,Double提供了一个isNaN方法,我们可以这样使用:

System.out.println(Double.isNaN(Double.NaN));

接下来我们看一个在代码中经常会用到的一个Double解析:

public void incorrectParse(String userInput){ doubleval = 0; try { val = Double.valueOf(userInput); } catch (NumberFormatException e) { } //do something for val }

这段代码有没有问题?咋看下好像没有问题,但是,如果我们的userInput是NaN,Infinity,或者-Infinity,Double.valueOf是可以解析得到结果的。

public void testNaN(){ System.out.println(Double.valueOf("NaN")); System.out.println(Double.valueOf("Infinity")); System.out.println(Double.valueOf("-Infinity")); }

运行输出:

NaNInfinity-Infinity

所以,我们还需要额外去判断NaN和Infinity:

public void correctParse(String userInput){ doubleval = 0; try { val = Double.valueOf(userInput); } catch (NumberFormatException e) { } if (Double.isInfinite(val)){ // Handle infinity error } if (Double.isNaN(val)) { // Handle NaN error } //do something for val }不要使用float或者double作为循环的计数器

考虑下面的代码:

for (float x = 0.1f; x Byte.MAX_VALUE)) { throw new ArithmeticException("Value is out of range"); } byte b = (byte) i; }

比如上面的例子中,我们将int转换成为byte,那么在转换之前,需要先判断int是否超出了byte的范围。

同时我们还需要考虑到精度的切换,看下面的例子:

public void intToFloat(){ System.out.println(subtraction(1111111111,1111111111)); } public int subtraction(int i , float j){ return i - (int)j; }

结果是多少呢?

答案不是0,而是-57。

为什么呢?

因为这里我们做了两次转换,第一次从1111111111转换到float,float虽然有32位,但是只有23位是存放真正的数值的,1位是符号位,剩下的8位是指数位。

所以从1111111111转换到float发送了精度丢失。

我们可以把subtraction方法修改一下,首先判断float的范围,如果超出了23bit的表示范围,则说明发送了精度丢失,我们需要抛出异常:

public int subtraction(int i , float j){ System.out.println(j); if ((j > 0x007fffff) || (j < -0x800000)) { throw new ArithmeticException("Insufficient precision"); } return i - (int)j; }

当然还有一种办法,我们可以用精度更高的double来做转换,double有52位来存放真正的数据,所以足够了。

public int subtractionWithDouble(int i , double j){ System.out.println(j); return i - (int)j; }到此,相信大家对"java中的Number怎么使用"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report