float to byte Java

After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast float to byte. The byte takes 1 byte of memory and float takes 4 bytes of memory. Assigning 4 bytes of memory to 1 byte of memory requires explicit casting. Moreover, float takes a mantissa (float-point value) but byte does not.

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 float to byte requires explicit casting.

Examples of implicit casting

int x = 10;
float y = x;

byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes

Following program explains explicit casting, Java style where a float is assigned to a byte.

public class Conversions
{
  public static void main(String args[])
  {
    float f1 = 10.5f;            // 4 bytes
    // byte b1 = f1;             // error as 4 bytes to 1 byte
          
    byte b1 = (byte) f1;         // 4 bytes type casted to 1 byte

    System.out.println("float value: " + f1);               // prints 10.5
    System.out.println("Converted byte value: " + b1);      // prints 10
  }
}


float to byte
Output screenshot of float to byte Java

float f1 = 10.5f;

We know earlier in data types, the float value must be suffixed with either F or f; else it is a compilation error.

byte b1 = f1;

The above statement raises a compilation error "possible loss of precision".

byte b1 = (byte) f1;

The float f1 is explicitly type casted to byte b1. Observe, the syntax of explicit casting. On both sides, it should be byte only. When casted, the precision of 0.5 is lost. This is known as data truncation. Always explicit casting looses precision or data truncation.

View all for 65 types of Conversions

1 thought on “float to byte Java”

Leave a Comment

Your email address will not be published.