Let’s talk about the "Java Long Divide Problem" today.

This article mainly introduces the problem of java long divisor, friends in need can refer to it


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?

Look at the following code output:


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. In the end what happened?

This is because the calculation of the constant L1 "really" overflows. Although the result of the calculation is suitable for putting into long and there is room for it, this result is not suitable for putting into int. This calculation is performed entirely by int operation, and only after the operation is completed, the result is promoted to long, and it is too late at this time: the calculation has overflowed, and it returns a value that is 200 times smaller . From int to long is a widening primitive conversion, which preserves the (incorrect) value. This value is then divisible by L2, and the calculation of L2 is correct because it is suitable for int operations. The result of this division is 5.

So why is the int operation performed? Because all factors multiplied together are int values. When you multiply two int values, you will get another int value. Java does not have the characteristic of determining the type of the target, but a language characteristic, which means that the type of the variable that stores the result will affect the type used in the calculation.

By using long constants instead of int constants as the first factor of each product, this program can be easily corrected.

The lesson is simple: when you are manipulating large numbers, beware of overflows. Even if the variable used to store the result appears to be large enough, it does not mean that the calculation that produces the result is of the correct type. When you are in doubt, use the long operation to perform the entire calculation.

The above is the whole content of this article, I hope it will be helpful to everyone's study, and I hope everyone will support you

The latest high-frequency interview questions collected in 2021 (all organized into documents), there are a lot of dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations. There are also detailed learning plans and interviews. Questions, etc., friends who need to obtain these content, please add Q Junyang: 547998459

Guess you like

Origin blog.csdn.net/p1830095583/article/details/114397294