Should I convert Integer to int?

I read streams where converting an integer to int is mandatory, BUT I came across this. My code is:

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); 

He gave me a warning about unnecessary unpacking on line 6 and recommended this to me instead:

 int sum = myint1 + myint2; //newline6 

Both prints gave me the same result. Is it necessary to convert Integer to int on line 6?

+5
source share
3 answers

The compiler will automatically do the same for unpacking (with JDK 5), therefore

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

a little redundant and

 int sum = myint1 + myint2; 

will have the same behavior.

However, you can parse String directly into int s and avoid both boxing and unpacking:

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

It's not needed.

According to jls , Integer will automatically unpack to int when you place them besides + .

Numeric contexts apply to the operands of an arithmetic operator.

Numeric contexts allow you to use:

  • conversion for unpacking (ยง5.1.8)
+4
source

If you use Java 1.5 or higher, you do not need to use Integer.intValue (), this is done by the compiler. Source: How to convert Integer to int?

+1
source

Source: https://habr.com/ru/post/1275570/


All Articles