0

Why can't the Java compiler directly cast an int to a Long?

long test = 1; // ok
Long test2 = 2; // does not compile!
Long test3 = 3L; // ok

It's especially frustrating since (of course) one can do

long test = 1;    
Long test2 = test;

Is it a deliberate design choice? What could go wrong if this was allowed?

Nicola Ambrosetti
  • 2,567
  • 3
  • 22
  • 38
  • 1
    For `Long test2 = 2;` to work, 2 implicit conversions would be required (`int` to `long` then `long` to `Long`). What do you think about that? – ernest_k Mar 05 '19 at 12:47
  • @ernest_k I'd be completely fine with that! – Nicola Ambrosetti Mar 05 '19 at 12:54
  • 1
    To make it even worse, this compiles: `Short test4 = 4;`. https://stackoverflow.com/questions/14425606/wrapper-classes-why-integer-literals-fail-for-long-but-work-for-anything-small – Thilo Mar 05 '19 at 12:55
  • @Thilo all the more reason to be consistent and allow it also for widening. In addition shortening is generally unsafe. – Nicola Ambrosetti Mar 05 '19 at 13:05

1 Answers1

1

An int is a primitive data type in Java. long is a primitive data type too, but Long is not a primitive data type. The implicit conversion does not work that way. You have to explicitly tell Java to convert to an object of type Long.

It is possible to implicitly cast a long to a Long because it is a single implicit conversion. From int to Long would be two conversions in one step which is not supported.

For the integer suffix syntax 100L see JLS 3.1. The L sets the type of the value to longinstead of int, which is the default case for integral types.

Markus Steppberger
  • 618
  • 1
  • 8
  • 18