Possible loss of error accuracy in java

This is my code:

class test{

    public static void main(String arg[]){

        int a=10, b=20;
        float c = 30.123;
        int e = (int)c;
        System.out.println(e);

    }
}

I get this error:

test.java:6: error: possible loss of precision
        float c = 30.123;
                  ^
required: float
found:    double
1 error

Why is all this?

+5
source share
2 answers

Floating point literals are of type by default double. And assigning a double value to the float type will result in some precision error. You can either change type cto doubleor add fat the end of this word to make it floatas follows:

float c = 30.123f;
+13
source

If you specify a float value without f at the end, it is treated as doublethat by default.

double d = 30.123;

For a floating literal, you must add f at the end of the float value.

float c = 30.123f;
+2
source

All Articles