saga
saga

Reputation: 93

Lossy conversion from long to int altough using int literal in int range

I do understand that a long literal can't suit an int variable, as long as I don't cast it:

long y = 1000000L;
int x = y;  // error - lossy conversion

What I don't understand is why using a int literal in the int range would produce the same error:

long y = 100;
int x = y;  // error - lossy conversion

The default literal for integers is 'int', so why am I not able to do this kind of operation? The only answer that comes to me is because while declaring a variable as long, Java stores the value as a long value, even if I don't append the "L" suffix, but I would want an 'official' explanation.

Upvotes: 2

Views: 157

Answers (2)

Itamar Lev
Itamar Lev

Reputation: 84

Your question looked simple in the beginning however after looking into it a bit I found a concept I haven't heard of before - implicit type-casting

As you stated the memory size taken for int and long is different: int - 32-bit signed integer long - 64-bit signed integer

And the problem in assigning a long value to an int is because of the size difference. the compiler will not perform numeric operations on your long value to check if it can fit into a 32-bit signed integer. for example the number 1 is represented differently in memory:

int 1 is "00000000 00000000 00000000 00000001" (32-bit).

long 1 is "00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001" (64-bit).

so we cannot perform implicit type casting on the data types which are not compatible Converting long int to int will cause dropping of excess high order bits.

However the other way around is applicable! it is called implicit type-casting or type promotion and because of it you can assign an int to a long variable.

java primitive types in depth https://www.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html

about type promotion http://www.java2s.com/Tutorials/Java/Data_Types/What_is_Java_type_promotion.htm

Upvotes: 0

Eran
Eran

Reputation: 393791

Even though you store in y a value that is small enough to fit in an int variable, a new value can be assigned to that variable later, and that later value may not fit in an int.

Since such an assignment may take place in runtime, the compiler has no way of being sure that the assignment will always be value.

The compiler can't statically analyze all your code to verify that the assignment will always be valid. Even though it looks like an easy validation in your simple example, in general it's not simple.

Upvotes: 6

Related Questions