先来看段代码
1
2
3
4
5
6
7
8
9
10
11
12
|
public class integerdemo {
public static void main(string[] args) {
string num = null ;
system.out.println( integer.parseint(num)); // exception java.lang.numberformatexception
system.out.println( integer.valueof(num)); // exception java.lang.numberformatexception
system.out.println( string.valueof(num)); //输出null
num = "" ;
system.out.println( integer.parseint(num)); // exception java.lang.numberformatexception
system.out.println( integer.valueof(num)); // exception java.lang.numberformatexception
system.out.println( string.valueof(num)); //空串,啥也不输出
}
}
|
先看一下 string.valueof() 里面是怎么写的
string.valueof() 在遇到 null 和 空串的情况下 ,都能正常输出,所以不抛错
再来看下 包装类型 integer里面又是如何处理的
这两个方法里面都需要先 parseint( s,10),就是将字符串s先转成 十进制的 int基本类型,,但是 valueof()会根据int范围从[-127,127]的内部缓存中去取(用到设计模式中的 享元模式)
一起来看下 parseint(s, 10),,在方法里面会判断字符串是否是合法的数字,会去校验null, 空串等其他格式,所以会抛错
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
public static int parseint(string s, int radix)
throws numberformatexception
{
/*
* warning: this method may be invoked early during vm initialization
* before integercache is initialized. care must be taken to not use
* the valueof method.
*/
if (s == null ) {
throw new numberformatexception( "null" );
}
if (radix < character.min_radix) {
throw new numberformatexception( "radix " + radix +
" less than character.min_radix" );
}
if (radix > character.max_radix) {
throw new numberformatexception( "radix " + radix +
" greater than character.max_radix" );
}
int result = 0 ;
boolean negative = false ;
int i = 0 , len = s.length();
int limit = -integer.max_value;
int multmin;
int digit;
if (len > 0 ) {
char firstchar = s.charat( 0 );
if (firstchar < '0' ) { // possible leading "+" or "-"
if (firstchar == '-' ) {
negative = true ;
limit = integer.min_value;
} else if (firstchar != '+' )
throw numberformatexception.forinputstring(s);
if (len == 1 ) // cannot have lone "+" or "-"
throw numberformatexception.forinputstring(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// accumulating negatively avoids surprises near max_value
digit = character.digit(s.charat(i++),radix);
if (digit < 0 ) {
throw numberformatexception.forinputstring(s);
}
if (result < multmin) {
throw numberformatexception.forinputstring(s);
}
result *= radix;
if (result < limit + digit) {
throw numberformatexception.forinputstring(s);
}
result -= digit;
}
} else {
throw numberformatexception.forinputstring(s);
}
return negative ? result : -result;
}
|
总结
以上所述是小编给大家介绍的java中integer.valueof,parsetint() string.valueof的区别和结果代码解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.cnblogs.com/quyf/p/9070298.html