简体   繁体   中英

The specifics of casting to int, from double and long

Hi so i recently saw a question structured much like this

int a= (int) Math.pow(2,32);
System.out.println(a); //prints out Integer.MAX_VALUE

After i answered the question it turns out i got it wrong, i answered Integer.MIN_VALUE but the correct answer was Integer.MAX_VALUE. After further testing i realized any double that i cast to an int that is greater than Integer.MAX_VALUE just makes the int equal to Integer.MAX_VALUE. For Example

int a = (int) ((double) Integer.MAX_VALUE+100);
System.out.println(a); //prints out Integer.MAX_VALUE

After further testing i realized if you try to cast a long to an int, it seems to assign the int to a seemingly random number.

So my question is. What the heck is going on, why does the double value not overflow the integer when you cast it to an int? and why does casting a long to an int return a seemingly random number

The logic of these conversions is part of the Java language specification, Item 5.1.3 .

You can see there, that when converting from long to int, most significant bits are discarded, leaving the least significant 32 bits.

And also, that if the result of rounding a double or float is a number that is too small or too large to represent as an int (or long ), the minimal or maximal representable number will be chosen.

There is no way for us here to answer "why" for a decision that has been made long ago. But this is the way the language is defined, and you can rely on it being the same in any Java environment you work in.

for casting a double value to integer it would erase the after point value and the the remainder is like rounding down the value of the double and for the first question the int would return the value it could save in 8 bites so it would seem to be the min.value long a= Math.pow(2,32); would give you the max.value and for casting long to an integer It's not a random number. It's the rightmost 32 bits of the long number sorry for my bad writing english is my second language

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