Long is 8 bytes in size, while how can it be "promoted" for float (4 bytes) in JAVA?

I read that in Java a long type can be raised by float and double ( http://www.javatpoint.com/method-overloading-in-java ). I wanted to ask that a long integer takes 8 bytes of memory in JAVA and a float takes 4 bytes, how does it work? Is it not possible that we can face data loss if we advance this way?

It is also noticeable that all promotions of a different type belong to a primitive type of a smaller size to similar or larger data types.

  • byte for short, int, long, float or double
  • short for int, long, float or double
  • char for int, long, float or double
  • int for long, float or double
  • long swim or double _______________ Exclusively In the case of Float
  • float for double
+7
java long-integer type-promotion
source share
3 answers

float is represented differently than integer types. For more information about the floating type, read the following: https://en.wikipedia.org/wiki/Single-precision_floating-point_format . The content generated down will look like this: the floating point format consists of a signed bit, 8 bits for the exponent and 23 bits for the fractional part of the value. The value is calculated as follows: (-1) ^ signbit * 1.fractionalpart * 2 ^ (exponent - 127). Thus, this algorithm allows us to represent larger values โ€‹โ€‹than the 64-bit integral type.

+7
source share

long uses more bytes, but has a smaller range: while long cannot exceed 2 63 float can go up to about 2 127 It is obvious that the extension of the range is associated with low accuracy, but since the range of float larger, the conversion from long to float is an advancement.

+11
source share

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 

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

+2
source share

All Articles