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?
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 String
s directly into int
s, and avoid both the boxing and the unboxing:
int myint1 = Integer.parseInt(numberOne);
int myint2 = Integer.parseInt(numberTwo);
int sum = myint1 + myint2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With