Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between Long a = Long.valueOf(1) or Long a = 1L?

Tags:

java

Just wondering if this and other related functions like those Integer is one of those things that one should not be bothered with and just go with Long a = 1L; simple and straightforward.

like image 954
non sequitor Avatar asked Oct 15 '09 05:10

non sequitor


2 Answers

They are essentially the same, the compiler internally creates a call to Long.valueOf() when it has to convert a primitive long to a Long, this is called "boxing".

In normal code you should use the primitive type long, it is more efficient than Long. You need Long only when you need objects, for example for putting long values into collections.

like image 102
starblue Avatar answered Nov 09 '22 10:11

starblue


Let's see what happens under the covers. First, consider this:

public class Example {
    public static void main(String[] args) {
        Long a = Long.valueOf(1L);
        System.out.println(a);
    }
}

Compile this with javac Example.java. Then disassemble it with javap -c Example. The result is the following:

Compiled from "Example.java"
public class Example extends java.lang.Object{
public Example();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   lconst_1
   1:   invokestatic    #2; //Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
   4:   astore_1
   5:   getstatic   #3; //Field java/lang/System.out:Ljava/io/PrintStream;
   8:   aload_1
   9:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/Object;)V
   12:  return

}

Ok, now change the program to the following:

public class Example {
    public static void main(String[] args) {
        Long a = 1L;
        System.out.println(a);
    }
}

Compile and disassemble it again.

You'll see that this version of the program compiles to exactly the same as the first version; the compiler has generated the call to Long.valueOf(...) automatically.

See: Autoboxing

like image 34
Jesper Avatar answered Nov 09 '22 11:11

Jesper