Java Integer valueOf() example

In this guide, you will learn about the Integer valueOf() method in Java programming and how to use it with an example.

1. Integer valueOf() Method Overview

Definition:

The valueOf() method of the Java Integer class returns an Integer object holding the value of the specified int or string.

Syntax:

1. Integer.valueOf(int i)
2. Integer.valueOf(String s)
3. Integer.valueOf(String s, int radix)

Parameters:

int i: The primitive integer value to be converted to an Integer object.

String s: The string to be parsed into an Integer object.

int radix: The base of the numeral system used in the string (only relevant for the third syntax, default is 10).

Key Points:

- The method provides a way to obtain Integer objects without using the new keyword.

- The valueOf() method is often used for boxing, i.e., converting a primitive int to an Integer object.

- If the string does not contain a parsable integer, a NumberFormatException will be thrown.

- The method is static, which means it's called on the class (Integer) rather than on an instance of the class.

2. Integer valueOf() Method Example

public class ValueOfExample {
    public static void main(String[] args) {
        // Convert primitive int to Integer object
        int num = 100;
        Integer intObject = Integer.valueOf(num);
        System.out.println("Integer object from int: " + intObject);

        // Convert String to Integer object
        String numberStr = "200";
        Integer intFromString = Integer.valueOf(numberStr);
        System.out.println("Integer object from string: " + intFromString);

        // Convert String in hexadecimal (base 16) to Integer object
        String hexStr = "1a";
        Integer intFromHex = Integer.valueOf(hexStr, 16);
        System.out.println("Integer object from hex string: " + intFromHex);
    }
}

Output:

Integer object from int: 100
Integer object from string: 200
Integer object from hex string: 26

Explanation:

In the example, we started by converting a primitive integer value (100) to an Integer object using the valueOf() method. 

We then parsed a string "200" to get its Integer representation. 

Lastly, we demonstrated the use of the radix parameter by parsing a hexadecimal string "1a" (which is 26 in base 10) into an Integer object.

Comments