Java – method overloading uses float to display “incompatible type error” but does not contain double
I tried overloading the code with this method, and I got an error
code:
class Adder { static float add(float a,float b) { return a + b; } static int add(int a,int b) { return a + b; } } class TestOverloading1 { public static void main(String[] args){ System.out.println(Adder.add(11.5,11.5)); System.out.println(Adder.add(27,21)); } }
In writing, 11.5f is in params, which is very effective
I know the difference between floating and double from here and here
So why does Java use parameters as double data types by default? Is the double precision behind this bias higher?
I know it needs to be doubled by default But I want to know what is the reason behind this?
Solution
Floating point literals without any suffix (for example, 11.5) are of type double (similarly, integer literals without any suffix are of type int)
The double parameter is not acceptable for methods that accept the float parameter (because the conversion from double to float may cause data loss, so the compiler will not automatically perform such conversion)
On the other hand, 11.5f is a float literal, so you can pass it to the add (float a, float b) method