float to short Java

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

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

Examples of implicit casting

short x = 10; // 2 bytes
float y = x; // 2 bytes to 4 bytes

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

Following program on float to short explains explicit casting. Observe, the Java syntax of explicit casting.

public class Conversions
{
  public static void main(String args[])
  {
    float f1 = 10.5f;                // 4 bytes
    // short s1 = f1;                // 4 bytes value to 2 bytes
          
    short s1 = (short) f1;           // 4 bytes value type casted to short

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


float to short
Output screenshot of float to short 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.

short s1 = f1;

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

short s1 = (short) f1;

The float f1 is explicitly type casted to short s1. Observe, the syntax of explicit casting. On both sides, it should be short only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation. Always explicit casting looses precision or data truncation.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.