Which is the difference between Long.valueOf(0) and 0L in Java?

Nothing.

Long b = 0L;

will undergo autoboxing. The compiler replaces it with:

Long b = Long.valueOf(0L);

You can see this if you decompile your class, e.g. using javap.

void a() {
  Long a = Long.valueOf(0);
}

void b() {
  Long b = 0L;
}

Decompiles to:

  void a();
    Code:
       0: lconst_0
       1: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       4: astore_1
       5: return

  void b();
    Code:
       0: lconst_0
       1: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       4: astore_1
       5: return

So how it is better initialize a variable, considering memory consumption and time complexity?

Because they are semantically identical, the memory consumption and time complexity is also identical.

Instead, focus on what is actually important, which is readability: use the one you (and others) will find most easy to understand at a glance.

Leave a Comment

tech