Assume that d is a double variable. Write an if statement that assigns d to the int variable i if the value in d is not larger than the maximum value for an int.
The method below is my attempt at this problem:
public static void assignInt(double d)
{
int i = 0;
if(d < Integer.MAX_VALUE)
i = (int)d;
System.out.print(i);
}
Integer.MAX_VALUE holds 2147483647. I am assuming this is the maximum value an int can hold? With this assumption in mind, I attempt to call assingDoubleToInt() three times:
public static void main(String[] args)
{
assignDoubleToInt(2147483646); //One less than the maximum value an int can hold
assignDoubleToInt(2147483647); //The maximum value an int can hold
assignDoubleToInt(2147483648);//One greater than the maximum value an int can hold. Causes error and does not run.
}
The first two calls output:
2147483646
0
And the third call, assignDoubleToInt(2147483648);, throws "The literal 2147483648 of type int is out of range." Isn't the comparison 2147483648 < 2147483647 here? Why is i being assigned the value if the comparison should evaluate to false?
Using the comparison d < Integer.MAX_VALUE is not the proper way to do this. How can I test whether a double variable can fit in an int variable?