Java - float type and integral types cast

Introduction

The value of all integral types (int, long, byte, short, and char) can be assigned to float data type without using an explicit cast.

int num1 = 15123; 
float salary = num1;            // Ok. int variable to float 
salary = 12455;                 // Ok. int literal to float 
float bigNum = 1226L;                 // Ok, a long literal to float 
float justAChar = 'A';          // Ok. Assigns 65.0F to justAChar 

A float value must be cast before assigning to integral data type.

  
int num1 = 10; 
float salary = 10.0F; 
num1 =  salary;      // An error. Cannot assign float to int 
num1 = (int)salary;  // Ok 

float point numbers approximation

Most floating-point numbers are approximation of their corresponding real numbers.

The assignment of int and long to float may result in loss of precision.

int num1 = 1999999999; // Stores an integer in num1 
float num2 = num1;     // Assigns the value stored in num1 to num2 
int num3 = (int)num2;  // Assigns the value stored in num2 to num3 

num1 and num3 are different.

Demo

public class Main {
  public static void main(String[] args) {
    int num1 = 1999999999; // Stores an integer in num1 
    float num2 = num1;     // Assigns the value stored in num1 to num2 
    int num3 = (int)num2;  // Assigns the value stored in num2 to num3 
  
    System.out.println(num1);/*  w w  w . ja  va2  s. c o m*/
    System.out.println(num2);
    System.out.println(num3);
  }
}

Result