Java中Integer.valueOf,parsetInt() String.valueOf的区别和结果代码解析
程序员文章站
2023-12-15 16:18:58
先来看段代码
public class integerdemo {
public static void main(string[] args) {...
先来看段代码
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, 空串等其他格式,所以会抛错
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的区别和结果代码解析,希望对大家有所帮助