6

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?

Tom
  • 16,842
  • 17
  • 45
  • 54
Shachi
  • 1,858
  • 3
  • 23
  • 41

5 Answers5

7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
4

doing

Adder.add(11.5,11.5)

is the same as

double a = 11.5;
double b = 11.5;
Adder.add(a, b)

that doesnt match the parameters in the static method

static float add(float a,float b){return a+b;}  

so you are required to: cast those literals to float:

Adder.add(11.5f, 11.5f );

or declare a and b as float

float a = 11.5;
float b = 11.5;
Adder.add(a, b)
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
2

"11.5" without nothing is considerated as double by Java. You can use something as :

System.out.println(Adder.add(new Float(11.5),new Float(11.5)));
Stéphane Ammar
  • 1,454
  • 10
  • 17
2

In Java when we type decimal number as 11.5, then it is considered as double. double is 64-bit while float is 32-bit so conversion is not possible, that's why compile time exception occurs. For more info please visit : Primitive Data Types

Mohit Tyagi
  • 2,788
  • 4
  • 17
  • 29
0

It is just a specification. Just like why int have default value 0 in Java.

Double is the default type for decimal values:

double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Javdroider
  • 136
  • 8