Should I convert Integer to int?

UpisDown :

I have read threads where the convertion of an Integer to an int is a must, BUT I encountered this thing. My code was :

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String numberOne = "12";

String numberTwo = "45";

Integer myint1 = Integer.valueOf(numberOne);

Integer myint2 = Integer.valueOf(numberTwo);

int sum = myint1.intValue() + myint2.intValue(); //line6

System.out.print(sum);

It gave me a warning of unnecessary unboxing at line6 and recommended me this instead:

int sum = myint1 + myint2; //newline6

Both prints gave me the same result. Isn't it a must to convert Integer to int at line 6?

Eran :

The compiler will do the same unboxing automatically for you (since JDK 5), so

int sum = myint1.intValue() + myint2.intValue();

is a bit redundant and

int sum = myint1 + myint2;

will have the same behavior.

That said, you can parse the Strings directly into ints, and avoid both the boxing and the unboxing:

int myint1 = Integer.parseInt(numberOne);
int myint2 = Integer.parseInt(numberTwo);
int sum = myint1 + myint2;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=472950&siteId=1