I've been writing Java for a while and have even been starting to teach it to others. I find it hard to explain to a new student why a float array's values must be casted. For example:
float[] someArray = {(float) 23.23, (float) 123.1, (float) 123.1};
int[] intArray = {12, 13, 4, 5};
double[] doubleArray = {22.12, 23.1, 12.1};
I'm guessing that the the values that include decimals are just treated as Doubles rather than floats, hence the need for casting. What is the reason that Java chooses it to be this way, couldn't the compiler also figure that because it is a float array, it will take float values?
Numbers with decimal points in Java are implicitly treated as double. Instead of casting to a float, you can simply write 23.23F, for example. The F at the end tells the compiler to treat the value as a float literal.
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