char to float Java

After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast char to float.

The float takes 4 bytes of memory and char takes 2 bytes of memory. 2 bytes memory value can be assigned to 4 bytes value and is done implicitly by JVM. But the reverse operation, float to char requires explicit casting.

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 int to short requires explicit casting.

Following program on char to float does the implicit casting operation of char to float (it is just simply an assignment).
public class Conversions
  public static void main(String args[])
    char ch = 'A';          // 2 bytes
    float f1 = ch;          // 2 bytes to 4 bytes

    System.out.println("char value: " + ch);              // A
    System.out.println("Converted float value: " + f1);   // prints 65.0 (ASCII value of A is 65)

char to float
Output screenshot of char to float Java

float f1 = ch;

The char ch is implicitly type casted to float f1. This is known as automatic promotion or widening conversion.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.