double to float Java

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.

byte –> short –> int –> long –> float –> double

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
   }
}


double to 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.

View all for 65 types of Conversions

3 thoughts on “double to float Java”

  1. Shouldn’t the following line:
    System.out.println(“double value: ” + f1); // prints 10.5, but as double

    Reference d1 instead of f1, like so:
    System.out.println(“double value: ” + d1); // prints 10.5, but as double

  2. Vikrant Chavan

    class A18
    {
    static int i=15, j=10;
    public static void main(String[] args)
    {

    A18 a18=new A18();
    a18.main(10);
    a18.main(10,123.5f);
    a18.main(99.9); //Type double parameter passed
    }
    static void main(int a)
    {
    System.out.println(“i=”+a);
    }
    void main(int j, float f)
    {
    System.out.println(“j=”+j);
    System.out.println(“f=”+f);
    }
    void main(float f) //A call to ‘a18.main(99.9);’ may go here
    {
    System.out.println(“f=”+f);
    }

    }

    My question is If I pass double type parameter in ” a18.main(99.9); ” and if it is not present Will it give a call to
    void main(float f)
    {
    System.out.println(“f=”+f);
    }

Leave a Comment

Your email address will not be published.