小編給大家分享一下Java中Integer.valueOf,parsetInt() String.valueOf的區(qū)別有哪些,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
目前創(chuàng)新互聯(lián)已為數(shù)千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、雅安服務(wù)器托管、網(wǎng)站托管、服務(wù)器租用、企業(yè)網(wǎng)站設(shè)計(jì)、平山網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
先來(lái)看段代碼
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 和 空串的情況下 ,都能正常輸出,所以不拋錯(cuò)
再來(lái)看下 包裝類型 Integer里面又是如何處理的
這兩個(gè)方法里面都需要先 parseInt( s,10),就是將字符串s先轉(zhuǎn)成 十進(jìn)制的 int基本類型,,但是 valueOf()會(huì)根據(jù)int范圍從[-127,127]的內(nèi)部緩存中去?。ㄓ玫皆O(shè)計(jì)模式中的 享元模式)
一起來(lái)看下 parseInt(s, 10),,在方法里面會(huì)判斷字符串是否是合法的數(shù)字,會(huì)去校驗(yàn)null, 空串等其他格式,所以會(huì)拋錯(cuò)
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; }
看完了這篇文章,相信你對(duì)“Java中Integer.valueOf,parsetInt() String.valueOf的區(qū)別有哪些”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!