Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Is There Any Reason to Use This Format: (long) 0; Instead of This One: 0L;?

Tags:

java

I couldn't find any information about this when searching StackOverflow or Google, and I've got some coworkers who disagree with my preference for how to initialize a simple Long variable.

Is there any reason to use one of these formats over the other?

Long foo = (long) 0; // First way of doing it
Long bar = 0L; // Second way of doing it

I'm most interested if anyone knows if there is an efficiency difference here.

The reason I prefer the second way is because you can specify values less than Integer.MIN_VALUE and greater than Integer.MAX_VALUE, whereas Eclipse would complain with something along the lines of "The literal 10000000000 of type int is out of range" if you used the first way here.

like image 674
Original Username Avatar asked Mar 12 '14 14:03

Original Username


2 Answers

There is no difference (except you mentioned). Compiler is smart enough. If I compile following class:

public class Test {
    public static void main(String[] args) {
        Long foo = (long) 0;
        Long bar = 0L;
    }
}

And then decompile them:

$ javap -c Test.class

Compiled from "Test.java"
public class Test {
  public Test();
    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_0      
       1: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       4: astore_1      
       5: lconst_0      
       6: invokestatic  #2                  // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       9: astore_2      
      10: return        
}

I don't see any difference. Use one which is look better for you or corresponds to the conventions.

To verify decompiler I compile this two lines independent and then calculate checksums:

$ sha1sum Test.class_L Test.class_long
292a93b6433b5a451afdb41bd957667c91eebf23  Test.class_L
292a93b6433b5a451afdb41bd957667c91eebf23  Test.class_long
like image 105
Anton Bessonov Avatar answered Sep 18 '22 14:09

Anton Bessonov


Long foo = (long) 0; // First way of doing it

This way will create an int then cast it to a long.

Long bar = 0L; // Second way of doing it

This is a long literal, so it will only create a long.

I imagine the difference is negligible, but it would be quicker to create a long than to create an int then cast to long.

Edit

As you correctly said, the first way will only allow you to convert an int to a long, which means that in one line, you can only ever create a long the size of an int.. which is pointless and a waste of memory.

like image 27
christopher Avatar answered Sep 18 '22 14:09

christopher