Integer valueOf() Method in Java (original) (raw)

The Integer.valueOf() method of the java.lang.Integer class is used to convert primitive values or strings into Integer objects. It is commonly preferred over constructors because it supports caching and better performance.

Why use valueOf() instead of new Integer()?

Method Variants of Integer.valueOf()

1. Integer.valueOf(int a)

Converts a primitive int value into its corresponding Integer wrapper object.

Syntax

public static Integer valueOf(_int a)

**Example 1: valueOf(int) with Positive Number

Java `

public class Geeks { public static void main(String[] args) {

    Integer value = Integer.valueOf(85);
    System.out.println("Output Value = " + value);
}

}

`

**Explanation:

**Example 2: valueOf(int) with Negative Number

Java `

public class Geeks { public static void main(String[] args) {

    Integer value = Integer.valueOf(-9185);
    System.out.println("Output Value = " + value);
}

}

`

Output

Output Value = -9185

**Explanation:

2: Integer.valueOf(String str)

The java.lang.Integer.valueOf(_String str) is an inbuilt method which is used to return an Integer object, holding the value of the specified String _str.

Syntax

public static Integer valueOf(_String str)

**Example 1: valueOf(String) with Positive Number

java `

public class Geeks { public static void main(String[] args) {

    String str = "424";
    Integer value = Integer.valueOf(str);

    System.out.println("Integer Value = " + value);
}

}

`

Output

Integer Value = 424

**Explanation:

**Example 2: valueOf(String) with Negative Number

Java `

public class Geeks { public static void main(String[] args) {

    String str = "-6156";
    Integer value = Integer.valueOf(str);

    System.out.println("Output Value = " + value);
}

}

`

Output

Output Value = -6156

**Explanation:

3. Integer.valueOf(String str, int radix)

The java.lang.Integer.valueOf(_String s, int radix) is an inbuilt method which returns an Integer object, holding the value extracted from the specified String when parsed with the base given by the second argument.

Syntax

public static Integer valueOf(String str, int radix)

**Parameter: The method accepts two parameters:

**Return Value : The method returns an Integer object holding the value represented by the string argument in the specified base or radix.

**Example 1: valueOf(String, radix)

Java `

public class Geeks { public static void main(String[] args) {

    Integer val1 = Integer.valueOf("1010", 8);
    Integer val2 = Integer.valueOf("1011", 16);
    Integer val3 = Integer.valueOf("1010", 2);
    Integer val4 = Integer.valueOf("1021", 10);

    System.out.println(val1);
    System.out.println(val2);
    System.out.println(val3);
    System.out.println(val4);
}

}

`