Shafny
Shafny

Reputation: 115

possible loss of precision error 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'm getting this error:

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

Why all these?

Upvotes: 6

Views: 25762

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213193

Floating point literals are by default of double type. And assigning a double value to a float type will result in some precision error. You can either change the type of c to double, or append an f at the end of it to make it float like so:

float c = 30.123f;

Upvotes: 14

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

If you specify float value without f at the end it is treated as double which is by-default.

double d = 30.123;

For float literal you should append f at the end of float value.

float c = 30.123f;

Upvotes: 2

Related Questions