什么是Integer.parseInt()源码
Integer.parseInt()方法的功能
Integer.parseInt()是Java中的一个内置方法,用于将字符串转换为整数类型。它接收一个字符串作为参数,并尝试将该字符串解析成一个整数值。如果成功解析,它将返回对应的整数值;如果解析失败,它将抛出一个NumberFormatException异常。
源码解析
Integer.parseInt()的源码相对比较简单,下面按照不同的步骤来解析它的源码:
步骤一:参数校验
首先,Integer.parseInt()会对传入的字符串参数进行校验,并判断是否为null或空字符串。如果参数为null或空字符串,则会直接抛出一个NumberFormatException异常。
```java
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
```
步骤二:解析字符串
在第一步通过校验后,接下来的步骤就是解析字符串。Integer.parseInt()方法会根据字符串中的字符逐个进行解析,并计算出最终的整数值。解析字符串的过程中,它会忽略字符串前导和尾随的空格。如果字符串中包含非法字符,则会抛出NumberFormatException异常。
```java
public static int parseInt(String s, int radix) throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
...
}
```
步骤三:根据进制进行计算
在步骤二完成字符串解析后,Integer.parseInt()方法会根据传入的进制参数radix将解析后的字符串转换成对应的整数值。radix参数表示要解析的字符串的进制,可以是2到36之间的任意整数。如果radix不在这个范围内,则会抛出NumberFormatException异常。
代码如下:
```java
public static int parseInt(String s, int radix) throws NumberFormatException {
...
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') {
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
} else {
digit = Character.digit(firstChar,radix);
if (digit < 0)
throw NumberFormatException.forInputString(s);
else
result = -digit;
}
multmin = limit / radix;
while (i < len) {
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;
}
```
整个Integer.parseInt()方法的源码解析到此结束。通过调用该方法,我们可以将一个字符串转换为整数类型,并进行进制转换,但需要注意输入的字符串必须符合整数格式,否则会抛出NumberFormatException异常。
猜您想看
-
大数据中QQ状态切换产生提示的解决方法是什么
1、大数据技术...
2023年05月26日 -
TDD、BDD、ATDD、DDD是什么
TDD是什么?...
2023年07月23日 -
如何正确使用闪光弹和震荡弹
使用闪光弹1、...
2023年05月15日 -
如何快速降低电脑的内存占用?
如何快速降低电...
2023年04月20日 -
如何在Windows系统中压缩和解压缩文件和文件夹
Windows...
2023年05月12日 -
Linux DRM基本组件有哪些
1. Linu...
2023年05月22日