简体   繁体   中英

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

long uses more bytes, but it has a smaller range: while long cannot go above 2 63 , float can go to about 2 127 . 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.

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.

This quick test should show why:

public class Main {

    public static void main(String[] args) {
        System.out.println("Float: " + Float.MAX_VALUE);
        System.out.println("Long: " + Long.MAX_VALUE);
    }
}

Ouput:

Float: 3.4028235E38
Long: 9223372036854775807

Note the scientific notation in the Float line. The Float takes up less space, but due to its representation, it can hold up to a larger number than a Long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM