Recently I stumbled over code where people write stuff like
Long myLong = Long.valueOf(42);
// instead of
Long myLong = 42L;
I have no clue why one would do this, except for personal taste regarding readability.
Am I missing something?
valueOf() is a built-in method in Java of lang class that returns a Long object holding the value extracted from a specified String S when parsed with the radix that is given in the second argument.
float s and long sTo specify a numeric literal as a long instead of an int , add an L (for long ) to the end of the literal. Either capital or lowercase will work, but a lowercase 'l' can easily be confused with the numeral '1', especially in monospace fonts.
The L suffix tells the compiler that we have a long number literal. Java byte , short , int and long types are used do represent fixed precision numbers. This means that they can represent a limited amount of integers. The largest integer number that a long type can represent is 9223372036854775807.
long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1.
with direct assignment you are required to cast if assigning int
to Long
(int
to primitive long
is implicit) and they get autoboxed
automatically using Long.valueOf
Long myLong1 = Long.valueOf(42);
Long myLong2 = Long.valueOf(42L);
Long myLong3 = 42L;
Long myLong4 = (long) 42;
otherwise they are all same See bytecode output from javap
public static void main(java.lang.String[]);
Code:
0: ldc2_w #16 // long 42l
3: invokestatic #18 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
6: astore_1
7: ldc2_w #16 // long 42l
10: invokestatic #18 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
13: astore_2
14: ldc2_w #16 // long 42l
17: invokestatic #18 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
20: astore_3
21: ldc2_w #16 // long 42l
24: invokestatic #18 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
27: astore 4
29: return
However using new Long(42L)
should be avoided if not absolutely necessary and one of above statement needs to be used in favor of this as valueOf
methods normally cache a range of values (FlyWeight Design Pattern
) by JVM internally
Trivia: In case of integers & Oracle JVM the range can be controlled using -XX:AutoBoxCacheMax=
The snippet
Long myLong = 42L;
is internally the same as
Long myLong = Long.valueOf(42);
The compiler will generate the same bytecode.
I also think it's a reminder of java before java5, where there was no autoboxing, and where
Long l = 42L;
could not be compiled.
They are equivalent, compiler will build the same bytecode for both
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With