After knowing primitive data types and Java rules of data Type Casting (Type Conversion), let us cast double to float. By memory-wise, double takes 8 bytes of memory and float take 4 bytes. Both differ in their precision storing.
See the data types order to know the brief rules of casting.
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like double to float requires explicit casting.
Examples of implicit casting
float price = 10.5;
double rate = price.
byte x = 10;
int y = x;
Following program on double to float explains explicit casting. Observe, the Java syntax of explicit casting.
public class Conversions
public static void main(String args)
double d1 = 10.5; // 8 bytes
// float f1 = d1; // error, double to float, no implicit
float f1 = (float) d1; // explicit casting
System.out.println("double value: " + f1); // prints 10.5, but as double
System.out.println("Converted float value: " + f1); // prints 10.5, but as float
Output Screenshot of double to float Java
float f1 = d1;
The above statement raises a compilation error as 8 bytes value cannot be assigned to a 4 bytes value implicitly. For this reason it is commented out. It requires explicit casting.
float f1 = (float) d1;
The double d1 is explicitly type casted to float f1. Observe, the syntax of explicit casting. On both sides, it should be float only. It is known as narrowing conversion.