Search code examples
javaunboxing

unboxing - how it becomes a better way to explicitly use intValue() compared to unboxing by itself


I was reading O'REILLY Java8 pocket guide when I came across this advise about unboxing [On page 30]

Note: For these examples, primitive variables end with a capitalP. This is not the convention.

The following example shows an acceptable but not recommended use of unboxing

Establish the weight allowance

weightLimitP = weightLimitP + weightAllowanceW;

It is better to write this expression with the intValue() method, as shown here:

weightLimitP = weightLimitP + weightAllowanceW.intValue();

Question: What I would like to know here is why is the second approach a better way? I mean, in what terms is it 'better'. How is it different from unboxing by itself

Note: The wrapper class in this example is Integer


Solution

  • Those two code snippets will generate exactly the same bytecode. So "better" is purely a matter of style and, thus, opinion.