简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM