In this tutorial, you will learn how to convert a float
value to a double
in Java, with examples to demonstrate implicit and explicit conversion methods.
Java – Convert float to double
Converting float to double in Java – In Java, a float
value can be converted to a double
in two ways: implicitly and explicitly. Since double
has a larger range than float
, this conversion is straightforward and can be handled by Java automatically.
Implicit Conversion from float to double
Java automatically performs an implicit (widening) conversion from float
to double
. This happens because double
has a larger memory size and range than float
, so there’s no risk of data loss.
Example of Implicit Conversion
public class FloatToDoubleExample {
public static void main(String[] args) {
float floatVal = 3.14f;
double doubleVal = floatVal; // Implicit conversion from float to double
System.out.println("Float value: " + floatVal);
System.out.println("Double value after conversion: " + doubleVal);
}
}
Output
Float value: 3.14
Double value after conversion: 3.140000104904175
In this example, the float
value 3.14
is automatically converted to a double
without any explicit cast.
Explicit Conversion from float to double
Although implicit conversion is straightforward, you can also explicitly cast a float
to double
to make your code more readable.
Example of Explicit Conversion
public class FloatToDoubleExample {
public static void main(String[] args) {
float floatVal = 3.14f;
double doubleVal = (double) floatVal; // Explicit conversion
System.out.println("Float value: " + floatVal);
System.out.println("Double value after explicit conversion: " + doubleVal);
}
}
Output
Float value: 3.14
Double value after explicit conversion: 3.140000104904175
In this example, the float
value is explicitly cast to a double
, even though this is unnecessary for widening conversions. This can sometimes enhance code readability.
Conclusion
Converting a float
to a double
in Java is simple due to implicit widening. Java handles this conversion automatically, but explicit casting is also an option if you prefer clarity in your code.