[英]Casting an int into a long
I have a question regarding the conversion from int into long in java. 我有一个关于在java中从int转换为long的问题。 Why for floats there is no problem: 为什么浮标没有问题:
float f = (float)45.45;//compiles no issue.
float f = 45.45f; //compiles no issue.
However for the long type it seems to be a problem: 但是对于长型,它似乎是一个问题:
long l = (long)12213213213;
//with L or l at the end it will work though.
long l = (long)12213213213L;
It seems that once the compiler notify an error due to an out-of-range issue it blocks there without checking for any possible casting that the programmer might have planned. 似乎一旦编译器因超出范围的问题而通知错误,它就会在那里阻塞而不检查程序员可能已经计划的任何可能的转换。
What's your take on it? 你对它有什么看法? Why is it like that there is any particular reason? 为什么有任何特殊原因?
Thanks in advance. 提前致谢。
However for the long type it seems to be a problem: 但是对于长型,它似乎是一个问题:
That's because 12213213213
without L
is an int
, and not long
. 那是因为没有L
的12213213213
是一个int
,并且不long
。 And since that value is outside the range of the int
, so you get an error. 由于该值超出了int
的范围,因此您会收到错误。
Try something like:- 尝试类似的东西: -
System.out.println(Integer.MAX_VALUE);
System.out.println(12213213213L);
you will understand better. 你会明白的。
As far as the case of float
is concerned: - 就float
的情况而言: -
float f = (float)45.45;
the value 45.45
is a double
value, and fits the size of double
. 值45.45
是一个double
值,适合double
的大小。 So, the compiler will have not problem with that, and then it will perform a cast
to float
. 因此,编译器将没有这一问题,然后它会执行一个cast
给float
。
It seems that once the compiler notify an error due to an out-of-range issue it blocks there without checking for any possible casting that the programmer might have planned. 似乎一旦编译器因超出范围的问题而通知错误,它就会在那里阻塞而不检查程序员可能已经计划的任何可能的转换。
Exactly. 究竟。 The compiler first checks for a valid value first, here int
, only then it can move further with the cast operation. 编译器首先检查一个有效值,这里是int
,然后才能通过强制转换操作进一步移动。
So, basically in case of long
and int
: - 所以,基本上在long
和int
情况下: -
long l = (long)12213213213;
you are not getting error because of the cast
operation, rather because your numeric literal
is not representable as int
. 你没有得到错误,因为中cast
操作,而是因为你的numeric literal
是不能表示为int
。 So, compiler didn't get the valid value there, to perform a cast operation. 因此,编译器没有获得有效值,以执行强制转换操作。
Java doesn't consider what you do with a value only what it is. Java不会考虑您只对值进行的操作。 For example if you have a long value which is too large it doesn't matter that you assign it to a double, the long value is checked as valid first. 例如,如果您有一个太大的值,那么将它分配给double是没关系的,则将long值首先检查为有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.