4

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

spiderman
  • 10,892
  • 12
  • 50
  • 84
  • Surely the pocket guide said something about why the author thinks it's "better"? – T.J. Crowder Jun 17 '16 at 08:25
  • nope. i'm reading O'REILLY Java 8 pocket guide - page 30 – spiderman Jun 17 '16 at 08:26
  • 2
    I'd double-check if I were you. I normally expect better of O'Reilly (even in a pocket guide). – T.J. Crowder Jun 17 '16 at 08:28
  • 4
    From Java 5 onward, those two code snippets will generate [exactly the same bytecode](http://stackoverflow.com/questions/6915823/which-is-better-in-terms-of-performance-implicit-auto-unboxing-or-explicit-un). So "better" is purely a matter of style, which is opinion-based. Also related: http://stackoverflow.com/questions/9331059/getting-intvalue-from-integer-does-it-make-any-sense, http://stackoverflow.com/questions/15985928/what-is-the-need-of-an-intvalue-method-if-wrappers-use-unboxing – T.J. Crowder Jun 17 '16 at 08:29
  • 1
    Only difference is writing style. both the codes are equal in terms of bytecode. – Sanjeev Jun 17 '16 at 08:31
  • Thank you @T.J.Crowder for the relative links and explanation. – spiderman Jun 17 '16 at 09:07

2 Answers2

1

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

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

It compiles to the same code. But it might be considered to be better style. Reason: one now can see at one glance that a NullPointerException might be raised or that it is a wrapper class, and a primitive class would be better.

This to the adage that code is read more often than written.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138