Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long is of size 8 bytes then how can it be 'promoted' to float(4 bytes) in JAVA?

I read that in Java the long type can be promoted float and double ( http://www.javatpoint.com/method-overloading-in-java ). I wanted to ask that long integer takes 8 bytes of memory in JAVA and float takes 4 bytes then how this promotion works? Isn't it possible that we could be facing some data loss if we promote this way?

Also it is noticeable that all other type promotions are from smaller size primitive datatype to similar or larger size datatypes.

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double _______________ Exceptional In case Of Float
  • float to double
like image 267
SMagic Avatar asked Jul 18 '15 21:07

SMagic


2 Answers

long uses more bytes, but it has a smaller range: while long cannot go above 263, float can go to about 2127. Obviously, the expansion of range comes at the price of lower precision, but since the range of float is larger, the conversion from long to float is a promotion.

like image 154
Sergey Kalinichenko Avatar answered Oct 03 '22 10:10

Sergey Kalinichenko


float is represented in a different way than integral types. For further infos on the floating-type, read this: https://en.wikipedia.org/wiki/Single-precision_floating-point_format . The content cooked down would look like this: the floating-point format consists of a sign-bit, 8 bits for the exponent and 23 bits for the fractional part of the value. The value is calculated like this: (-1)^signbit * 1.fractionalpart * 2 ^ (exponent - 127). Thus this algorithm allows representation of larger values than a 64bit integral type.

like image 38
Paul Avatar answered Oct 03 '22 09:10

Paul