Unboxing Long in java
Asked Answered
M

9

2

In some code I see this:

private void compute(Long a, Long b, Long c) {
        long result = a-(b+c);
...

It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.

Are there any reason that a result should be stored as a primitive?

Moreland answered 31/5, 2013 at 10:30 Comment(6)
A more serious question is why Long has been used at all. It is far less efficient.Handoff
It is stored as a primitive because you have declared it as a primitive.Rothberg
Perhaps you can find some clues here linkBorreri
@dmiller2117 I suppose what he meant is that he is reading someone else's code and wondering, why this someone used the primitive type there.Centromere
It's also funny that a void method has a local variable called "result" ... but I guess it would mean something else :PKhorma
If you ever do this yourself, consider whether or not any of a, b and c might be null, as you'll get a not-very-obvious NullPointerException when the autounboxing calls .longValue() on them in the expression.Khorma
L
6

It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.

No, what is "strange" is that you can use the + and - operators on Long objects. Before Java 5, this would have been a syntax error. Then autoboxing/unboxing was introduced. What you're seeing in this code is autounboxing: the operators require primtives, so the compiler automatically inserts a call to longValue() on the objects. The arithmetic is then performed on primitive long values, and the result is also a long that can be stored without further conversion on the variable.

As for why the code does this, the real question is why someone would use the Long type instead of long. Possible reasons:

  • The values come from some library/API that delivers Long values.
  • The values are stored in collections (List, Map), which cannot hold primitives.
  • Sloppiness or cargo cult programming.
  • The ability to have null values is required, e.g. to signal unavailable or uninitialized data.

Note that the ability of Long to hold null values means that the calculation (or more specifically, the longValue() calls inserted by the compiler) can fail with a NullPointerException - a possibility the code should deal with somehow.

Lepine answered 31/5, 2013 at 10:57 Comment(0)
A
1

The reason is obvious: result is declared as primitive.

Auditory answered 31/5, 2013 at 10:33 Comment(2)
That's actually not the reason.Lepine
I don't see why this is not the reason. If under "result" you understand the declared variable, then this is the reason. If under "result" you understand the result of the operation "a-(b+c)", then the reason is that the addition operation is defined for primitives and this is why the Longs are auto-unboxed before being added.Auditory
S
1

The arithmetic operators + and - are not defined for boxed types (e.g. Long) but for primitive types (e.g. long).

The result is also a long. See Autoboxing and Unboxing tutorial

Autoboxing this into a Long would result in a small performance cost. It is also unnecessary because

  1. We know it will be non-null (if a, b or c were null, a NullPointerException would occur).
  2. It would be autoboxed implicitly if we use it later where a Long is required.
Suggs answered 31/5, 2013 at 11:5 Comment(0)
M
0

Based on your needs.I mean the decelaration.

Autoboxing and unboxing can happen anywhere where an object is expected and primitive type is available

Merrymaker answered 31/5, 2013 at 10:32 Comment(0)
N
0

Usually you should prefer using primitives, especially if you are certain they cannot be null. If you insist on using the boxed types always think extra hard about what happens when it is null. Java will do the boxing and unboxing automatically for you, but staring at an int and wondering why you got a NullPointerException can be fun.

Neilneila answered 31/5, 2013 at 10:34 Comment(0)
V
0

From Java 1.5 onwards, autoboxing and unboxing occurs implicitly whenever needed.

Voroshilov answered 31/5, 2013 at 10:34 Comment(0)
H
0

The following line:

long result = a-(b+c);

...asks Java to take the result of the expression using 3 Longs, and then store it in a primitive long. Before Java 5, it would complain about the types not matching - but these days it just assumes you mean what you say and automatically does the conversion from object to primitive type for you.

In this example however, unless there's some other good reason not presented here, there's absolutely no point having the parameters as the boxed, object type in the first place.

Huehuebner answered 31/5, 2013 at 10:48 Comment(0)
G
0

As per the javadoc

Boxing conversion converts expressions of primitive 
type to corresponding expressions of reference type. 
Specifically, the following nine conversions are called the boxing conversions:

From type boolean to type Boolean

From type byte to type Byte

From type short to type Short

From type char to type Character

From type int to type Integer

From type long to type Long

From type float to type Float

From type double to type Double

From the null type to the null type


Ideally, boxing a given primitive value p, would always yield an identical reference.     
In practice, this may not be feasible using existing implementation techniques. The  
rules above are a pragmatic compromise. The final clause above requires that certain 
common values always be boxed into indistinguishable objects. The implementation may  
cache these, lazily or eagerly. For other values, this formulation disallows any 
assumptions about the identity of the boxed values on the programmer's part. This would 
allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without     
imposing an undue performance penalty, especially on small devices. Less memory-limited 
implementations might, for example, cache all char and short values, as well as int and 
long values in the range of -32K to +32K.`

Here is the Oracle Doc source

Gatefold answered 31/5, 2013 at 10:58 Comment(0)
B
-1

The answer for your doubt is

  1. autoboxing and autounboxing in Java which converts from primitive to wrapper class objects and vice versa respectively.
  2. autoboxing means internally compiler uses valueOf() method of primitive classes ans autounboxing means internally compiler uses xxxValue() method.
  3. Suppose for private void compute(Long a, Long b, Long c) { long result = a-(b+c);

its makes this conversion a.longValue()-(b.longValue()+c.longValue()) Which means even before your statement performs addition the compiler provides the primitives of long type as input to your operands Remember that this goes in hand as JAVA is statically and strongly typed language.

Hence you get long type output

I hope i cleared your doubt

Besotted answered 16/5, 2019 at 19:20 Comment(4)
Hey there, firstly your answer is not really an answer, as the mechanism you are explaining here (autoboxing & unboxing), converting Long objects to long primitives, could also convert the result to a Long object if it was Long result = a-(b+c);. Secondly and lastly, your post is poorly formatted, the 1/2/3 structure makes no sense at all.Murderous
Sure Sir if your claiming this as wrong then please enlighten me with Correct analysis. and more ever if Long result there then again there will be an auto-boxing stepBesotted
I won't, because that's not why I was here. I am simply reviewing late answers. I'm just saying that your answer isn't helpful, as it is just saying the same stuffs as the answer by Michael Borgwardt, which was posted the same day as the question. But his is better formatted, explained / developed. If you want to help others, answer questions that needs to be, and care about the helpfulness and formatting of it.Murderous
Thank You for the reply .Sure Will take of your advise in futureBesotted

© 2022 - 2024 — McMap. All rights reserved.