I tried this method overloading code and I got the error
no suitable method found for add(double,double)
The 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));
}
}
On writing, 11.5f in params, this works well.
I understood the differences between float and double from here and here.
So, why does Java take the parameters as double datatype by default? Is the higher precision of double behind such a bias?
I am aware that it takes the double by default. But, I wish to know what is the reason behind this?
A floating point literal without any suffix (such as 11.5
) is of type double
by definition (similarly an integer literal without any suffix is of type int
).
A double
parameter is not acceptable for a method that accepts float
arguments (since a casting from double
to float
may result in loss of data, and therefore the compiler won't perform such casting automatically).
On the other hand, 11.5f
is a float
literal, so you can pass such literals to your add(float a,float b)
method.