📜  Integer.valueOf() 与 Integer.parseInt() 示例

📅  最后修改于: 2021-09-14 02:15:33             🧑  作者: Mango

Integer.parseInt():

在对字符串操作时,有时我们需要将表示为字符串转换为整数类型。 Java通常用于将 String 转换为 Integer 的方法是parseInt() 。该方法属于Java.lang 包中的Integer 类。它接受一个有效的字符串作为参数并将其解析为原始数据类型 int。它只接受 String 作为参数,在传递任何其他数据类型的值时,由于类型不兼容,它会产生错误。

此方法有两种变体:

句法:

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

例子:

// Java program to demonstrate working parseInt()
  
public class GFG {
    public static void main(String args[])
    {
        int decimalExample = Integer.parseInt("20");
        int signedPositiveExample = Integer.parseInt("+20");
        int signedNegativeExample = Integer.parseInt("-20");
        int radixExample = Integer.parseInt("20", 16);
        int stringExample = Integer.parseInt("geeks", 29);
  
        System.out.println(decimalExample);
        System.out.println(signedPositiveExample);
        System.out.println(signedNegativeExample);
        System.out.println(radixExample);
        System.out.println(stringExample);
    }
}
输出:
20
20
-20
32
11670324

Integer.valueOf():

此方法是属于Java.lang 包的静态方法,它返回相关的整数对象,其中包含传递的参数的值。此方法可以将整数或字符串作为参数。但是当给定的 String 无效时,它会提供一个错误。此方法也可以接受一个字符作为参数,但输出将是其对应的 Unicode 值。此方法将始终缓存 -128 到 127(含)范围内的值,并且可能缓存此范围之外的其他值。

句法:

public static Integer valueOf(int a)
public static Integer valueOf(String str)
public static Integer valueOf(String str, int base)

例子:

// Java program to illustrate the
// java.lang.Integer.valueOf(int a)
import java.lang.*;
  
public class Geeks {
  
    public static void main(String[] args)
    {
  
        Integer obj = new Integer(10);
  
        // Returns an Integer instance
        // representing the specified int value
        System.out.println("Output Value = "
                           + obj.valueOf(85));
    }
}
输出:
Output Value = 85

Integer.parseInt() 和 Integer.valueOf() 的区别

  1. Integer.valueOf() 返回一个 Integer 对象,而 Integer.parseInt() 返回一个原始 int。
    // Program to show the use
    // of Integer.parseInt() method
      
    class Test1 {
        public static void main(String args[])
        {
            String s = "77";
      
            // Primitive int is returned
            int str = Integer.parseInt(s);
            System.out.print(str);
      
            // Integer object is returned
            int str1 = Integer.valueOf(s);
            System.out.print(str1);
        }
    }
    
    输出:
    7777
    
  2. String 和 integer 都可以作为参数传递给 Integer.valueOf() 而只有 String 可以作为参数传递给 Integer.parseInt()。
    // Program to show that Integer.parseInt()
    // cannot take integer as parameter
      
    class Test3 {
        public static void main(String args[])
        {
            int val = 99;
      
            try {
      
                // It can take int as a parameter
                int str1 = Integer.valueOf(val);
                System.out.print(str1);
      
                // It cannot take an int as a parameter
                // Hence will throw an exception
                int str = Integer.parseInt(val);
                System.out.print(str);
            }
            catch (Exception e) {
                System.out.print(e);
            }
        }
    }
    

    编译错误:

    prog.java:18: error: incompatible types:
    int cannot be converted to String
                int str = Integer.parseInt(val);
                                           ^
    1 error
    
  3. Integer.valueOf() 可以将字符作为参数并返回其相应的 unicode 值,而 Integer.parseInt() 将在将字符作为参数传递时产生错误。
    // Program to test the method
    // when a character is passed as a parameter
      
    class Test3 {
        public static void main(String args[])
        {
            char val = 'A';
      
            try {
      
                // It can take char as a parameter
                int str1 = Integer.valueOf(val);
                System.out.print(str1);
      
                // It cannot take char as a parameter
                // Hence will throw an exception
                int str = Integer.parseInt(val);
                System.out.print(str);
            }
            catch (Exception e) {
                System.out.print(e);
            }
        }
    }
    

    编译错误:

    prog.java:18: error: incompatible types:
    char cannot be converted to String
                int str = Integer.parseInt(val);
                                           ^
    1 error
    
    

差异表

Integer.parseInt() Integer.valueOf()
It can only take a String as a parameter. It can take a String as well as an integer as parameter.
It returns a primitive int value. It returns an Integer object.
When an integer is passed as parameter, it produces an error due to incompatible types When an integer is passed as parameter, it returns an Integer object corresponding to the given parameter.
This method produces an error(incompatible types) when a character is passed as parameter. This method can take a character as parameter and will return the corresponding unicode.
This lags behind in terms of performance since parsing a string takes a lot of time when compared to generating one. This method is likely to yield significantly better space and time performance by caching frequently requested values.
If we need the primitive int datatype then Integer.parseInt() method is to be used. If Wrapper Integer object is needed then valueOf() method is to be used.