3

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?

4
  • 2
    float f = 23.23f; Commented Oct 29, 2018 at 1:07
  • 2
    A "raw" decimal value defaults to double, hence you must specify a float if you want to use it as such. Either via a cast as you do, or as a float literal as Scary Wombat suggests. The compiler could assume you meant float, but that might not be what you want, hence the warning/error. Commented Oct 29, 2018 at 1:09
  • 1
    Unlike a conversion from a wider integer type to a narrower integer type, a conversion from double to float can change the value, because the double value must be rounded to fit in the float precision. So I presume the Java designers do not allow implicit double to float conversions to avoid this change in value without an explicit request by the programmer. The specific rules for conversions allowed for assignments are here, but I am not familiar enough with the Java specification to interpret it readily and… Commented Oct 29, 2018 at 3:00
  • … say whether those are the specific rules that govern the specific code you ask about. Commented Oct 29, 2018 at 3:00

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.