Copy Code code as follows:
public class change{
public static void Main (String args[]) {
Final Long l1=24* 60 * 60 * 1000 * 1000;
Final Long l2=24* 60 * 60 * 1000;
System.out.println (L1/L2);
}
}
/**
* Output:5
*/
Why is the output 5?
Then look at the following code output:
Copy Code code as follows:
public class change{
public static void Main (String args[]) {
Final Long l1=24l* 60 * 60 * 1000 * 1000;
Final Long l2=24l* 60 * 60 * 1000;
System.out.println (L1/L2);
}
}
/**
* output:1000
*/
The output of this is the result we want. What the hell happened?
This is because the calculation of the constant L1 "really" overflowed. Although the result of the calculation is suitable for a long and there is more space in it, the result is not fit to be placed in an int. This calculation is performed entirely as an int, and only after the operation has finished, the result is raised to long, and it is too late: the computation has overflowed, and it returns a value that is 200 times times smaller. from int to Long is a widening of the original type conversion, which retains the (incorrect) value. This value is then divisible by L2, and the L2 is correct because it is suitable for int operations. So the result of dividing evenly is 5.
So why is the int operation performed? Because all the factors that multiply together are int values. When you multiply two int values, you get another int value. Java does not have an attribute of a target-specific type, just a language attribute, meaning that the type of variable that stores the result affects the type used by the calculation.
By using a long constant instead of the int constant as the first factor in each product, you can easily revise the program.
The lesson is simple: when you're working on a lot of numbers, be wary of overflows, even if the variables used to save the results seem large enough, and it doesn't mean that the resulting calculation has the correct type. When you are unsure, use a long operation to perform the entire calculation.