Java - convert double to float

I saw an example where the following code is used to convert double to float:

Double.valueOf(someDouble).floatValue()

I would just do it like

(float)someDouble

Is there an advantage to using the first?

+4
source share
1 answer

Looking at the implementation Double floatValue():

/**
 * Returns the value of this {@code Double} as a {@code float}
 * after a narrowing primitive conversion.
 *
 * @return  the {@code double} value represented by this object
 *          converted to type {@code float}
 * @jls 5.1.3 Narrowing Primitive Conversions
 * @since JDK1.0
 */
public float floatValue() {
    return (float)value;
}

It looks like it behaves exactly the same as your casting. Therefore, it makes no sense to use it.

+9
source

Source: https://habr.com/ru/post/1669142/


All Articles