I'm practicing debugging and there is a question that i'm unsure on, it's asking what is wrong and what can I do to fix it I read the book chapter on it but not specific enough. pasted from the book:
int a = 26.4 ^ When you compile, this is the message:
Test.Java:8: possible loss of precision int a = 26.4;
required: int found : double 1 error
I have a decent understanding on why there is an error, because of how double has a higher precedence than int and how an int cant necessarily store a double value.
My question is, is there a way to type cast variable a into a double type? Or is the only way to fix this by changing a from int to double?
thanks
The only possibilities you have are:
Type cast the double into an int if you want to store your number as an integer:
int a = (int)26.4 // so a will be 26
(you will obviously lose precision this way)
Store the number as a double to keep the precision:
double a = 26.4
Casting will not help at anything, look at the code below:
//int a = 26.4; // gives compile error
int a = (int) 26.4; // gives 26
double b = a; // gives 26.0
double c = (double) a; // also gives 26.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With