Java.lang Package Classes

Java Integer - valueOf() Method



The java.lang.Integer.valueOf() method returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseInt(java.lang.String, int) method. The result is an Integer object that represents the integer value specified by the string.

In other words, this method returns an Integer object equal to the value of: new Integer(Integer.parseInt(s, radix)).

Syntax

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

Parameters

s Specify the string to be parsed.
radix Specify the radix to be used in interpreting s.

Return Value

Returns a Integer object holding the value represented by the string argument in the specified radix.

Exception

Throws NumberFormatException, if the String does not contain a parsable int.

Example:

In the example below, the java.lang.Integer.valueOf() method returns a Integer object holding the value given by the specified String and parsed with the specified radix.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating a string holding int value
    String x = "100";
    String y = "6F";

    //creating Integer object using radix as 2 (binary)
    Integer p = Integer.valueOf(x, 2);

    //creating Integer object using radix as 16 (hexadecimal)
    Integer q = Integer.valueOf(y, 16);

    //printing the string
    System.out.println("The string x is: " + x); 
    System.out.println("The string y is: " + y); 

    //printing the Integer object 
    System.out.println("The Integer object p is: " + p);   
    System.out.println("The Integer object q is: " + q);    
  }
}

The output of the above code will be:

The string x is: 100
The string y is: 6F
The Integer object p is: 4
The Integer object q is: 111

❮ Java.lang - Integer