简体   繁体   中英

Casting a long to an Int returns in '-1'?

Is it safe to cast a long to an int in Java?

For some reason, the following code, I get '-1' as anIntVar. And I have checked 'aLongVar' is not an -1.

public static final long CONST = 1000 * 62;

long aLongVar
int anIntVar =  (int)(aLongVar/ CONST);

If it was safe it wouldn't require an explicit cast.

No, its not safe. Don't do it. Because, A Long / long has 64 bit and can hold much more data than an Integer / int has 32 bit only. Doing the conversion will result in loss of information.

If at all you wish to do it, do like this

Use the .intValue() to convert the Long value to an int value.

A long is 64 bits, and an int is 32 bits, so no, it's not safe.

Try

int anIntVar = Math.rint(aLongVar);

You can cast a long to an int and get meaningful results if the value in the long will fit in an int. If not, you will get high bits truncated. In your example you don't show what was in the numerator before you did the division, but -1 is certainly not an impossible value given the right inputs.

Is it legal? Yes. Is it safe? No, not unless you do range checks, or are confident that you know your inputs well enough.

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