先來看段代碼
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