user3287264
user3287264

Reputation:

Wrapper Classes, Difference in functionality when creating object via a String parameter in Constructor?

In terms of instances of wrapper classes, does the instance behave differently when the instance is created via a String arg in the constructor in comparison to an int, double etc.

E.g is there a difference in:

Integer wrapperInt= new Integer(33);

Integer wrapperInt2= new Integer("33");

Upvotes: 0

Views: 1192

Answers (4)

The answer is that yes, there can be a difference between the two syntaxes. Specifically, the syntax

new Integer(33);

results in the value 33 being interpreted as an integer constant by the compiler and stored as a literal in the code. By contrast, the syntax

new Integer("33");

results in a call that routes the string value through Integer.parseInt(s, 10). This matters if the value in question has a leading zero character; in the case of an int literal, the compiler will evaluate the literal as octal:

new Integer(010); // equals 8

By contrast, the string constructor will always evaluate the value as base 10:

new Integer("010"); // equals 10

In any case, you should almost always be using Integer.valueOf(), as it is usually more efficient.

Upvotes: 0

Srikanth Ganji
Srikanth Ganji

Reputation: 1157

The only difference is you will be creating a string object unnecessarily in the second approach and it will try to parse the string you have passed to the constructor, If it couldn't parse the string then it will throw NumberFormatException.

Upvotes: 0

Jesper
Jesper

Reputation: 206836

The end result will be the same - you'll have an Integer object with the value 33.

The version that takes a String will throw a NumberFormatException if the input string cannot be parsed.

Note: There's no need to write a statement like Integer wrapperInt = new Integer(33);. Let the compiler do it for you (auto-boxing):

Integer wrapperInt = 33;

If, for some reason, you do not want to use auto-boxing, then at least use Integer.valueOf(...) instead of using the constructor:

Integer wrapperInt = Integer.valueOf(33);

This is more efficient; the valueOf method can return a cached object (so that it's not necessary to create a new Integer object).

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691755

No, it doesn't. Both instances represent the integer 33. If there was a difference, it would be written in the javadoc.

Note that you should favor the usage of the factory methods instead:

Integer i = Integer.valueOf(33);
i = Integer.valueOf("33");

Upvotes: 2

Related Questions