Use parseInt to create wrapper objects

Viewed 430

I’m reading the book Beginning Java 9 fundamentals and in relation to creating wrapper objects the author says:

“All wrapper classes are immutable. They provide three ways to create their objects:

1-Using constructors.

2-Using the valueOf() factory methods.

3-Using parseXxx() method, where Xxx is the name of the wrapper class. It is not available in the Character class.

The first and the second point I have clear, but the third I do not finish to understand it completely. But the API says that Integer.parseXxx returns a primitive. Does it make any sense?

3 Answers

Yes, the static method Integer.parseInt(String) attempts to parse the given string into a primitive integer. Failing to do that, it will throw an exception.

So basically, there is no need to wrap it, as it guaranteed either succeeding, or "letting you know" it couldn't by throwing.

The only way I see using parseXxx to create a wrapper object is to actually have the target type be a wrapper type itself. i.e:

Integer number = Integer.parseInt("123");

Yet, parseInt is not really creating a wrapper object but rather the value returned by parseInt is being autoboxed to its corresponding wrapper type.

A look at the source code of Integer class confirms that Integer.parseInt returns int primitive. Below is how the method signature,

public static int parseInt(String s, int radix)

The api basically Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, for api to work.

And it can be used as below, in java program, to get the int primitive from String

int newInt = Integer.parseInt("99");
Related