简体   繁体   English

关于显式铸造的JAVA SE7问题

[英]JAVA SE7 questions about explicit casting

I'm preparing Java OCA exam. 我正在准备Java OCA考试。

And here is a questions about casting. 这是关于铸造的问题。 I understand that for primitive data types, if we trying to assign an int to long, we should be fine. 我理解,对于原始数据类型,如果我们尝试将int分配给long,我们应该没问题。 Since it can be done automatically. 因为它可以自动完成。

And if we trying to assign a long to an int. 如果我们尝试将long分配给int。 It cause a compiler error, right? 它会导致编译错误,对吧?

So, the first question: when the explicit casting is needed and I didn't do that in my code, The code won't compile. 所以, 第一个问题:当需要显式转换并且我没有在我的代码中执行此操作时,代码将无法编译。 Is there any case that the code will compile?? 有没有代码会编译?

And the second question : The book I'm reading actually has a switch case structure like: int num = 10 switch (num) case 10/3: //do something.. 第二个问题 :我正在阅读的书实际上有一个开关案例结构,如:int num = 10 switch(num)case 10/3://做点什么..

and the author says that, in this case, the decimal result will be chopped to 3.... But, there is no explicit casting over here, I think this should be a compile error... 并且作者说,在这种情况下,十进制结果将被切割为3 ....但是,这里没有明确的转换,我认为这应该是编译错误...

As for the first question: if explicit casting is needed, the code won't compile. 至于第一个问题:如果需要显式转换,代码将无法编译。 That's what "needed" means. 这就是“需要”的意思。

As for the second question, try this: 至于第二个问题,试试这个:

double x = 10/3;

x will be equal to 3 too. x也将等于3。 It's not casting, it's the standard behaviour of / operator. 它不是强制转换,它是/运算符的标准行为。

First question - generally any typecast conversion that causes a loss of data / accuracy must be made explicitly. 第一个问题 - 通常必须明确地进行导致数据/准确性丢失的任何类型转换。

For example: 例如:

int y = 3;
double x = y;                 // ok

Results in the value 3.0 stored in x and is perfectly legal. 结果存储在x中的值3.0是完全合法的。 however: 然而:

double x = 3.0;
int y = x;                // give a compile error

int y = (int) x;          // must explicit cast

Second question - Think of operators as functions so division function is (<T> first, <T> second) so the division operator changes its behavior based on the two types passed to it. 第二个问题 - 将运算符视为函数,因此除法函数是(<T> first, <T> second)因此除法运算符根据传递给它的两种类型改变其行为。 so 10/3 equals 3 an integer because it's a divison of two integers and 10.0/3 equals 3.3333333 because it cannot convert double to int (without explicitly being told to do so) therefore it converts the int (3) to a double and performs the calculation on doubles and returns a double. 所以10/3等于3一个整数,因为它是两个整数的分区10.0 / 3等于3.3333333,因为它不能将double转换为int(没有明确告知这样做)因此它将int(3)转换为double并执行对双精度计算并返回一个双精度数。

So the return type of an operator is dependent on its arguments and automatic typecast will always be upward (more accuracy) if possible. 因此,运算符的返回类型取决于其参数,如果可能,自动类型转换将始终向上(更准确)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM