Difference Between parseInt() and valueOf() in Java – Java中parseInt()和valueOf()的区别

最后修改: 2022年 6月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

As we know, converting a numeric String to an int or Integer is a very common operation in Java.

我们知道,将数字String转换为intInteger是Java中一个非常常见的操作。

In this tutorial, we’ll go through two very popular static methods, parseInt() and valueOf() of the  java.lang.Integer class which help us do this conversion. Moreover, we’ll also understand a few differences between these two methods using simple examples.

在本教程中,我们将通过java.lang.Integer类中两个非常流行的静态方法,parseInt()valueOf()来帮助我们进行这种转换。此外,我们还将通过简单的例子了解这两种方法之间的一些区别。

2. The parseInt() Method

2、parseInt()方法

The class java.lang.Integer provides three variants of the parseInt() method. Let’s look at each of them.

java.lang.Integer提供了parseInt()方法的三种变体。让我们来看看它们各自的情况。

2.1. Convert String to Integer

2.1.将字符串转换为整数

The first variant of parseInt() accepts a String as a parameter and returns the primitive data type int. It throws NumberFormatException when it cannot convert the String to an integer.

parseInt()的第一个变体接受一个String作为参数,并返回原始数据类型int。当它不能将String转换为整数时,会抛出NumberFormatException

Let’s look at its signature:

让我们来看看它的签名。

public static int parseInt(String s) throws NumberFormatException

Now, we’ll see a few examples where we pass signed/unsigned numeric strings as parameters to it to understand how parsing from string to integer happens:

现在,我们将看到几个例子,我们将有符号/无符号的数字字符串作为参数传递给它,以了解从字符串到整数的解析如何发生。

@Test
public void whenValidNumericStringIsPassed_thenShouldConvertToPrimitiveInt() {
    assertEquals(11, Integer.parseInt("11")); 
    assertEquals(11, Integer.parseInt("+11")); 
    assertEquals(-11, Integer.parseInt("-11"));
}

2.2. Specifying Radix

2.2.指定Radix

The second variant of the parseInt() method accepts a String and an int as parameters and returns the primitive data type int. Just like the first variant we saw, it also throws NumberFormatException when it cannot convert the String to an integer:

parseInt()方法的第二个变体接受一个String和一个int作为参数并返回原始数据类型int。就像我们看到的第一个变量一样当它不能将String转换为整数时,它也会抛出NumberFormatException

public static int parseInt(String s, int radix) throws NumberFormatException

By default, the parseInt() method assumes that the given String is a base-10 integer. Here, the parameter radix is the radix or base to be used for string to integer conversion.

默认情况下,parseInt()方法假定给定的String是一个base-10的整数。这里,参数radixradix或base,用于字符串到整数的转换。

To understand this better, let’s look at a few examples where we pass a string along with the radix parameter to parseInt():

为了更好地理解这一点,让我们看几个例子,我们把一个字符串和radix参数一起传递给parseInt()

@Test
public void whenValidNumericStringWithRadixIsPassed_thenShouldConvertToPrimitiveInt() {
    assertEquals(17, Integer.parseInt("11", 16));
    assertEquals(10, Integer.parseInt("A", 16)); 
    assertEquals(7, Integer.parseInt("7", 8));
}

Now, let’s understand how string conversion with radix takes place. For instance, in a number system with radix 13, a string of digits such as 398 denotes the decimal number (with radix/base 10) 632. In other words, in this case, here’s how the calculation happens – 3 × 132 + 9 × 131 + 8 × 130 = 632.

现在,让我们了解一下小数点的字符串转换是如何进行的。例如,在小数点13的数字系统中,一串数字如398表示小数(小数点/基数10)632。换句话说,在这种情况下,计算过程是这样的–3 × 132 + 9 × 131 + 8 × 130 = 632。

Similarly, in the above example Integer.parseInt(“11”, 16) returned 17 with calculation, 1 × 161 + 1 × 160 = 17.

同样,在上面的例子中Integer.parseInt(“11”, 16)返回17,计算结果是1 × 161 + 1 × 160=17。

2.3. Convert Substring to Integer

2.3.将子串转换为整数

Lastly, the third variant of the parseInt() method accepts a CharSequence, two integers beginIndex and endIndex of the substring, and another integer radix as parameters. If any invalid string is passed, it throws NumberFormatException:

最后,parseInt()方法的第三个变体接受一个CharSequence,两个整数beginIndexendIndex的子串,以及另一个整数radix作为参数。如果传递任何无效的字符串,它会抛出 NumberFormatException:

public static int parseInt(CharSequence s, int beginIndex, int endIndex, int radix) throws NumberFormatException

JDK 9 introduced this static method in the Integer class. Now, let’s see it in action:

JDK 9在Integer类中引入了这个static方法。现在,让我们看看它的作用。

@Test
public void whenValidNumericStringWithRadixAndSubstringIsPassed_thenShouldConvertToPrimitiveInt() {
    assertEquals(5, Integer.parseInt("100101", 3, 6, 2));
    assertEquals(101, Integer.parseInt("100101", 3, 6, 10));
}

Let’s understand how substring conversion to integer with a given radix takes place. Here, string is “100101”, beginIndex and endIndex are 3 and 6, respectively. Hence, the substring is “101”. For expectedNumber1, radix passed is 2, which means it’s binary. Therefore, substring “101” is converted to integer 5. Further, for expectedNumber2, the radix passed is 10, which means it is decimal. Consequently, substring “101” is converted to integer 101.

让我们了解一下子串是如何转换为给定小数的整数的。这里,字符串是 “100101”,beginIndexendIndex分别为3和6。因此,子串是 “101”。对于expectedNumber1,传递的radix是2,这意味着它是二进制。因此,子串 “101 “被转换为整数5。此外,对于expectedNumber2,,传递的radix是10,这意味着它是十进制的。因此,子串 “101 “被转换为整数101。

Additionally, we can see that Integer.parseInt() throws NumberFormatException when any invalid string is passed:

此外,我们可以看到,Integer.parseInt() 在传递任何无效的字符串时,会抛出NumberFormatException

@Test(expected = NumberFormatException.class)
public void whenInValidNumericStringIsPassed_thenShouldThrowNumberFormatException(){
    int number = Integer.parseInt("abcd");
}

3. The valueOf() Method

3. valueOf() 方法

Next, let’s take a look at the three variants of the valueOf() method provided by the class java.lang.Integer.

接下来,让我们看看valueOf()类提供的三种变体java.lang.Integer.的方法。

3.1. Convert String to Integer

3.1.将字符串转换为整数

The first variant of the valueOf() method accepts a String as a parameter and returns the wrapper class Integer. If any non-numeric string is passed, it throws NumberFormatException:

valueOf()方法的第一个变体接受一个字符串作为参数,并返回封装类Integer。如果传递任何非数字字符串,它会抛出NumberFormatException

public static Integer valueOf(String s) throws NumberFormatException

Interestingly, it uses parseInt(String s, int radix) in its implementation.

有趣的是,它的实现中使用了parseInt(String s, int radix)

Next, let’s see a few examples of conversion from signed/unsigned numeric string to integer:

接下来,让我们看几个从有符号/无符号数字字符串转换为整数的例子。

@Test
public void whenValidNumericStringIsPassed_thenShouldConvertToInteger() {
    Integer expectedNumber = 11;
    Integer expectedNegativeNumber = -11;
        
    assertEquals(expectedNumber, Integer.valueOf("11"));
    assertEquals(expectedNumber, Integer.valueOf("+11"));
    assertEquals(expectedNegativeNumber, Integer.valueOf("-11"));
}

3.2. Convert int to Integer

3.2.将int转换为Integer

The second variant of valueOf() accepts an int as a parameter and returns the wrapper class Integer. Also, it generates a compile-time error if any other data type such as float is passed to it.

valueOf()的第二个变体接受一个int作为参数,并返回封装类Integer.同时,如果任何其他数据类型(如float)被传递给它,它会产生一个编译时错误

Here’s its signature:

这是它的签名。

public static Integer valueOf(int i)

In addition to int to Integer conversion, this method can also accept a char as a parameter and returns its Unicode value.

除了intInteger的转换,这个方法还可以接受一个char作为参数并返回其Unicode值。

To understand this further, let’s see a few examples:

为了进一步理解这一点,让我们看几个例子。

@Test
public void whenNumberIsPassed_thenShouldConvertToInteger() {
    Integer expectedNumber = 11;
    Integer expectedNegativeNumber = -11;
    Integer expectedUnicodeValue = 65;
        
    assertEquals(expectedNumber, Integer.valueOf(11));
    assertEquals(expectedNumber, Integer.valueOf(+11));
    assertEquals(expectedNegativeNumber, Integer.valueOf(-11));
    assertEquals(expectedUnicodeValue, Integer.valueOf('A'));
}

3.3. Specifying Radix

3.3.指定Radix

The third variant of valueOf() accepts a String and an int as parameters and returns the wrapper class Integer. Also, like all the other variants we’ve seen, it also throws NumberFormatException when it cannot convert the given string to Integer type:

valueOf()的第三个变体接受一个字符串和一个int作为参数,并返回封装类Integer。此外,像我们看到的所有其他变体一样,当它不能将给定的字符串转换成Integer类型时,它也抛出NumberFormatException

public static Integer valueOf(String s, int radix) throws NumberFormatException

This method also uses parseInt(String s, int radix) in its implementation.

该方法在实现中也使用了parseInt(String s, int radix)

By default, the valueOf() method assumes that the given String represents a base-10 integer. Additionally, this method accepts another argument to change the default radix.

默认情况下,valueOf()方法假定给定的String代表一个base-10的整数。此外,这个方法还接受另一个参数来改变默认的小数位数.

Let’s parse a few String objects:

让我们来解析几个String对象。

@Test
public void whenValidNumericStringWithRadixIsPassed_thenShouldConvertToInetger() {
    Integer expectedNumber1 = 17;
    Integer expectedNumber2 = 10;
    Integer expectedNumber3 = 7;
        
    assertEquals(expectedNumber1, Integer.valueOf("11", 16));
    assertEquals(expectedNumber2, Integer.valueOf("A", 16));
    assertEquals(expectedNumber3, Integer.valueOf("7", 8));
}

4. Differences Between parseInt() and valueOf()

4.parseInt()valueOf()之间的区别

To sum up, here are the main differences between the valueOf() and parseInt() methods:

总结一下,这里是valueOf()和parseInt()方法的主要区别。

Integer.valueOf() Integer.parseInt()
It returns an Integer object. It returns a primitive int.
This method accepts String and int as parameters. This method accepts only String as the parameter.
It uses Integer.parseInt() in its method implementation. It doesn’t use any helper method to parse the string as an integer.
This method accepts a character as a parameter and returns its Unicode value. This method will produce an incompatible types error on passing a character as a parameter.

5. Conclusion

5.总结

In this article, we learnt about the different implementations of parseInt() and valueOf() methods of the java.lang.Integer class. We also looked at the differences between the two methods.

在这篇文章中,我们学习了parseInt()valueOf()类的不同实现。我们还研究了这两个方法之间的差异。

As always, the complete code samples for this article can be found over on GitHub.

一如既往,本文的完整代码样本可以在GitHub上找到