0

In Java, the following line does not give compilation error

long a = 10;

But the following line throws compilation error "Incompatible type"

Long a = 10;

I know the above statement should be written as

Long a = 10L;

But I would like to understand why did JDK designers took the decision of not doing type conversion and then auto boxing and only doing one of them?

Keen Sage
  • 1,899
  • 5
  • 26
  • 44
  • 1
    1. `10` is a integer number literal, and java treats that as `int`. 2. It's not failing because `int` can be implicitly upcast to `long`. 3. Autoboxing `10` would make an `Integer` because `10` is an `int`. 4. If Java were to autobox in your second line, then that would make it `Long a = Integer.valueOf(10)`, but there's a problem there: `Long` is not a supertype of `Integer`. And the language designers said **no** to 2 implicit conversions (first upcast to `long`, then autobox to `Long`) – ernest_k Feb 19 '19 at 11:37
  • 3
    I don't understand the negative votes. It's a legitimate question that only Java designers are qualified to answer. Maybe it was to keep the compiler fast and simple. Maybe it was to protect the coder from bugs. E.g. what should happen if you wrote Long a = 'a'? – Igor F. Feb 19 '19 at 11:40
  • In Scala you can do `val a: Long = 10` so it seems like a reasonable question to me. The question is about language design, not what is the actual syntax of Java. – Simon Feb 19 '19 at 11:54
  • @kai what a stupid comparison – Coderino Javarino Feb 19 '19 at 11:55
  • @Simon that is again another story. Now that is about comparing languages. That indeed has an answer. Back in the days when Java was created they didn't want intergers as in c, that are overlapping and different on every os(implementation). They wanted to make a difference. It was at that time they pinned them to fixed sizes: 1L is something defined different than 1. Autoboxing came way later. Now Scala again does a lot different especialy in regard to parsing... – kai Feb 19 '19 at 18:51

2 Answers2

1

It's default behavior. To use a Long constant just add an "l" at the end of the number:

Long number = 10l;
Ayrton
  • 2,218
  • 1
  • 14
  • 25
0

The first example doesn't give compilation error because long type is wider than int. You can do assignment like:

double -> float -> long -> int -> short -> byte

The second example requires autoboxing, but java can autobox primitive types to corresponding wrappers only. E.g. long to Long, int to Integer,...

That's why to distinguish different types you can add letter:

5L - long, 5d - double, 5f- float

See here for more details Java: Why can't I cast int to Long

Ruslan
  • 6,090
  • 1
  • 21
  • 36