3

Is there any significant difference in casting a literal number vs. using a suffix on the literal number?

To illustrate...

doSomethingWithLong(2L); //vs...
doSomethingWithLong((long) 2);

To clarify: Let's assume that the code still compiles with the literal value that is used.

smp7d
  • 4,947
  • 2
  • 26
  • 48

3 Answers3

8

In the first one, you are using long literal. In the second one you are casting an integer literal to a long.

They won't behave the same, if the value is too big to be stored in an int type. For e.g., the 2nd code won't compile for value greater than Integer.MAX_VALUE, or less than Integer.MIN_VALUE.

You should also be very careful while performing arithmetics with integer literals. You might get unexpected result, when the result of the arithmetic operation, goes out of range. For e.g:

System.out.println(123456 * 123456); // Will print `-1938485248`

Related Post:


Let's assume that the code still compiles with the literal value that is used.

Assuming that you have literals for which the code compiles, there is no difference in bytecode. The above two invocations generates the same bytecode as you can see below. You can use javap -c YourClass command to see the bytecode:

0: ldc2_w        #2                  // long 2l
3: invokestatic  #4                  // Method doSomethingWithLong:(J)V
6: ldc2_w        #2                  // long 2l
9: invokestatic  #4                  // Method doSomethingWithLong:(J)V
Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
8

You wouldn't be able to compile

 doSomethingWithLong((long) 222222222222222222); 
 // The literal 222222222222222222 of type int is out of range 

Because 222222222222222222 doesn't fit in int.

You can read about the primitive data types in this official Java tutorial.

The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).

Let's assume that the code still compiles with the literal value that is used.

They are equivalent, see Rohit's byte code answer.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

Aside from certain things not compiling, you can get unexpected results if you are not careful - 5d/2d returns 2.5 5/2 returns 2