Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Integer.valueOf()

Returns an Integer wrapper object for a string or an int.

Available since: Java 1.0

Syntax

static Integer valueOf(String s)

Parameters

ParameterTypeDescription
sString / intA string with an integer, or an int value.

Return value

IntegerAn Integer object. For values from -128 to 127 the same cached object is returned.

Examples

valueOf() returns an object, parseInt() a primitive:

void main() {
    Integer boxed = Integer.valueOf("25");
    int plain = Integer.parseInt("25");
    List<Integer> list = new ArrayList<>();
    list.add(boxed);
    list.add(plain);
    IO.println(list);
}

Output:

[25, 25]

Notes

Usually the difference is invisible: Java converts int to Integer and back automatically (autoboxing). What matters is that Integer is an object, so compare it with equals(), and an Integer variable can be null, which throws NullPointerException when unboxed to int.

See also

  • Integer.parseInt() — Converts a string containing an integer to an int.
  • == vs equals() — == compares primitive values and object references; equals() compares object contents.
  • String.valueOf() — Converts a value of any type to a string.

Related recipes

In the tutorial

  • Type conversion — Automatic widening, explicit (int) casts, turning strings into numbers with Integer.parseInt and numbers into strings.

Thanks for reading!

Donate to the site — we work hard for you.