Why can't I change double to int? | Core Java Forum
H
Harika Posted on 14/06/2023

when i'm tyring to solve quiz i went through one question i.e., double d=78; int i=d; and i got answer like we cant convert double into int so it is compilation error. Here even though it is declared as double the value od double is with in the range of int only i.e., 78 value is in the range of int value only. then why can't we convert double into int.


Y
Yogesh Chawla Replied on 20/06/2023

Since double is a bigger data type than int, it needs to be down-casted.
See the syntax below:

int IntValue = (int) DoubleValue;

The code snippet below illustrates double to int typecasting in Java:

class DoubleToInt {
    public static void main( String args[] ) {
        double DoubleValue = 3.6987;
        int IntValue = (int) DoubleValue;
        System.out.println(DoubleValue + " is now " + IntValue);
    }
}

The output of this will be:
3.6987 is now 3

Please paste your question and then i will explain it better.