Reputation: 1045
I'm trying to do the following problem from "Core Java for the Impatient" -
"What happens when you cast a double to an int that is larger than the largest possible int value?"
Code:
package ch01.sec01;
import java.util.Random;
public class Exercise_5{
public static void main(String[] args){
int max = 10000;
int min = 1000;
Random rand = new Random();
double randomDouble = Integer.MAX_VALUE + rand.nextInt((max - min) + 1);
System.out.println("randomDouble: " +randomDouble);
int intFromDouble = (int)randomDouble;
System.out.println("intFromDouble: " +intFromDouble);
}
}
Output:
randomDouble: -2.147475257E9
intFromDouble: -2147475257
I'm wondering why randomDouble takes a negative value since primitve double has a wider range than primitive int and so there should be no overflow issues and what would be the correct way to get a double greater than Integer.MAX_VALUE?
Thanks
Upvotes: 1
Views: 1559
Reputation: 54168
Your line does not cast the 2 part as double, and then sum them, but it sum them which results in an overflow, and them you just put in a double
double randomDouble = Integer.MAX_VALUE + rand.nextInt((max - min) + 1);
Upvotes: 1
Reputation: 522109
In the expression:
double randomDouble = Integer.MAX_VALUE + rand.nextInt((max - min) + 1);
the right hand side of the expression will first assign the sum to an integer, then this result will be cast to a double. Since adding anything to Integer.MAX_VALUE
will result in overflow, you end up with a negative number, because the sign bit gets flipped as part of the overflow.
If you want a double, then just cast MAX_VALUE
to double
:
double randomDouble = (double)Integer.MAX_VALUE + (double)rand.nextInt((max - min) + 1);
Now in this case you get what you want, because you are adding a random number to a double, which is bearing the largest int value, which is not near the limit for what doubles can store.
Upvotes: 3
Reputation: 356
To put it simply: when you execute double randomDouble = Integer.MAX_VALUE + rand.nextInt((max - min) + 1);
the part that is actually overflowing (as an Integer, thus taking a negative value) is just Integer.MAX_VALUE + rand.nextInt((max - min) + 1)
which is subsequently casted to double.
Upvotes: 1