getting error: incompatible types: possible lossy conversion from double to float for type promotion code

599 views Asked by At

i didnt understand the error when executing below code.

public class Main{
    public static void main (String[] args) {
        byte b=2;
        short s=7;
        int i=11002;
        char c = 's';
        float f = 9.987;
        double d = .879;
        int res = (f*b) + (i/c) - (d*s);
        System.out.println("(f*b) + (i/c) - (d*s)");
        System.out.println("result = "+res);
    }
}

errors i get:

Main.java:7: error: incompatible types: possible lossy conversion from double to float float f = 9.987; ^ Main.java:9: error: incompatible types: possible lossy conversion from double to int int res = (fb) + (i/c) - (ds); ^ 2 errors

2

There are 2 answers

0
Akash Kumar On

I guess you are beginner in java . So the mistake you are making is typecasting . You can not assign double value to a float type .

Try this code

public class Main{
    public static void main (String[] args) {
        byte b=2;
        short s=7;
        int i=11002;
        char c = 's';
        float f = 9.987f;
        double d = .879;
        int res = (int) ((f*b) + (i/c) - (d*s));
        System.out.println("(f*b) + (i/c) - (d*s)");
        System.out.println("result = "+res);
    }
}

If you don't want to face this problem again in future learn about type casting (automatic conversion and explicit conversion).

0
Clement On

The result of an operation between different data types will always be the largest type (here double). If you want to keep the result as an int : look into casting values.

It should look like this : int res = (int) ((f*b) + (i/c) - (d*s))

Otherwise, make the result a double.

Also, floats in java need to have f at the end : float f = 9.987f;