将字符串转为Integer类型时,使用valueOf方法与使用parseInt()方法有何不同
时间: 2024-03-05 16:51:15 浏览: 27
使用valueOf方法和parseInt方法都可以将字符串转为Integer类型,但是它们有以下不同:
1. 返回值类型同:valueOf方法返回一个Integer对象,而方法返回一个int类型。
2. 对于非数字字符串的处理不同:当传入的字符串无法转为数字时,valueOf方法会抛出NumberFormatException异常,而parseInt方法会返回NaN(非数字)。
3. 参数不同:valueOf方法可以接受两个参数,第一个参数是字符串,第二个参数是进制数。而parseInt方法只接受一个参数,即要转换的字符串。
例如,对于字符串"123",使用valueOf方法可以这样调用:
```
String str = "123";
Integer num = Integer.valueOf(str);
```
而使用parseInt方法可以这样调用:
```
String str = "123";
int num = Integer.parseInt(str);
```
如果要将十六进制字符串"1A"转为Integer类型,可以使用valueOf方法这样调用:
```
String hexStr = "1A";
Integer num = Integer.valueOf(hexStr, 16);
```
而parseInt方法则需要先将十六进制字符串转为十进制字符串,再调用parseInt方法:
```
String hexStr = "1A";
int num = Integer.parseInt(Integer.toString(Integer.parseInt(hexStr, 16), 10));
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)