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
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.
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);/*from w ww.j a va2 s .com*/ System.out.println(num2); System.out.println(num3); } }