Java – after reasoning, l must be specified as long, F and D as float and double
Here are a few related questions
According to the title, why should you specify the variable type as long or float, double? Does the compiler not evaluate variable types?
Java believes that all integer literals are ints - is this to reduce the blow of unintentional memory waste? Double all floating-point text to ensure maximum accuracy?
Solution
When you have a constant, it looks the same, but there is no subtle difference between the values In addition, due to the introduction of automatic packing function, you get different results
Consider that if you multiply 0.1 by 0.1 as a floating-point number or double value and convert it to a floating-point number, you can get this value
float a = (float) (0.1 * 0.1); float b = 0.1f * 0.1f; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b));
a= 0.00999999977648258209228515625 b= 0.010000000707805156707763671875 a == b is false
Now compare the results of a calculation you performed using float or int
float a = 33333333f - 11111111f; float b = 33333333 - 11111111; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b));
a= 22222220 b= 22222222 a == b is false
Compare int and long
long a = 33333333 * 11111111; // overflows long b = 33333333L * 11111111L; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b));
a= -1846840301 b= 370370362962963 a == b is false
More double length
double a = 333333333333333333L / 333333333L; double b = 333333333333333333D / 333333333D; System.out.println("a= "+new BigDecimal(a)); System.out.println("b= "+new BigDecimal(b)); System.out.println("a == b is " + (a == b));
a= 1000000001 b= 1000000000.99999988079071044921875 a == b is false
In short, using int, long, double, or float may produce different results than using other types