1

I have encountered something strange today. The below code compiles unexpectedly and runs fine.

public class Test {

    public static void func(double d) {
        System.out.print("d : " + d);
    }

    public static void main(String[] args) {
        float f = 10.0f;
        func(f); // output: d : 10.0
    }
}

But this one gives compilation error

public class Test {

    public static void func(float f) {
        System.out.print("f : " + f);
    }

    public static void main(String[] args) {
        double d = 10.0d;
        func(d);
    }
}

Can somebody please explain this behaviour ?

Smile
  • 3,832
  • 3
  • 25
  • 39
Oğuzhan Aygün
  • 137
  • 1
  • 1
  • 13
  • 1
    Does this explain it? [float and double datatype in java](https://stackoverflow.com/questions/27598078/float-and-double-datatype-in-java/27598164) – ldz Dec 06 '19 at 11:13
  • No it does not explain this. its just compares float and double data types. But I wonder why java accepts float instead of double and not vice versa – Oğuzhan Aygün Dec 06 '19 at 11:18
  • 1
    Related: [Java: passing an argument with a different type to a function](https://stackoverflow.com/questions/13277655/java-passing-an-argument-with-a-different-type-to-a-function) and [Java overloading - long and float](https://stackoverflow.com/questions/43796767/java-overloading-long-and-float) – Mark Rotteveel Dec 07 '19 at 17:18

2 Answers2

4

Type promotion from float to double is safe as no data is lost and all float 4 bytes can fit into double 8 byes.

However the opposite, from double to float, always truncates the data as double 8 bytes can't fit into float 4 bytes. Compiler guards against doing this truncation accidentally by forcing the programmer to manually specify the type conversion.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • yes thats sounds reasonable but what if we ovverload the function ? it is going to be confusing for me :D – Oğuzhan Aygün Dec 06 '19 at 11:21
  • @OğuzhanAygün see [this answer](https://stackoverflow.com/questions/30109231/method-overload-resolution-in-java) but there are also gotchas [like this](https://stackoverflow.com/questions/54118123/why-compiler-thinks-byte-and-char-are-ambigious). – Karol Dowbecki Dec 06 '19 at 11:22
1

double(8 byte) is a bigger data type than float(4 byte) so you can store float(4 byte) in double(8 byte) but you can't double in float. If you try to do that you'll get Possible loss of precision error.

So the following will give error.

float f = 120.55;

While this one don't

double d = 120.44f;
Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15