Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I convert Integer to int?

Tags:

java

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?

like image 726
UpisDown Avatar asked Feb 25 '18 14:02

UpisDown


1 Answers

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;
like image 106
Eran Avatar answered Oct 03 '22 15:10

Eran