Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to assign Primitive value to a Wrapper class

What is a difference between in directly assigning a primitive value to a Wrapper type and using the valueOf API? i.e.

Long val = 91l;

and

Long val = Long.valueOf(91l);

This question arises from a bug that I have been breaking my head on for days now. So far I have not been able to recreate it successfully and would randomly come up. I have some objects which are generated as part of processing some data, these objects have numerous fields of which some are of type Long (Wrapper) I am sure that values are getting assigned to all of the variables, but in some cases they are just coming out NULL, even when there is no reason for that.

The manner in which this question is related is, the Set methods of these Long attributes actually take argument of type long (primitive) and were assigned using the first approach. I am not sure if that could be causing it. I have modified my code with the second approach and am waiting for some good testing to get completed before I be happy about fixing it.

I am keen to know if there is any theoretical difference in the above 2 methods that I have mentioned. (I usually use the first one most of the time.)

like image 697
Salman A. Kagzi Avatar asked Feb 21 '23 17:02

Salman A. Kagzi


1 Answers

Those two lines will compile to the same bytecode (at least in all compilers I've seen). It's not clear where your problem is, but it's not there. (It's not guaranteed by the spec how the value is created, but the result is guaranteed to be an object such that the longValue() method will return the original primitive value.)

For example, decompiling this method:

static void foo() {
    Long val1 = 91L;
    Long val2 = Long.valueOf(91L);
}

ends up with:

static void foo();
  Code:
   0:   ldc2_w  #2; //long 91l
   3:   invokestatic    #4; //Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
   6:   astore_0
   7:   ldc2_w  #2; //long 91l
   10:  invokestatic    #4; //Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
   13:  astore_1
   14:  return    
}

(As a small point, I'd encourage you to use L rather than l in source code as a suffix - l can look very much like 1 depending on your font.)

like image 200
Jon Skeet Avatar answered Mar 06 '23 10:03

Jon Skeet