简体   繁体   中英

JAVA SE7 questions about explicit casting

I'm preparing Java OCA exam.

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. Since it can be done automatically.

And if we trying to assign a long to an 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..

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...

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. 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. 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. 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.

So the return type of an operator is dependent on its arguments and automatic typecast will always be upward (more accuracy) if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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