Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can int/byte/short/long be converted to float/double without typecasting but vice-versa not possible

Tags:

java

variables

My code goes like this --

public void abc{     
 long a=1111;
 float b=a; // this works fine even though this is narrowing conversion
 long c=b;// this gives compilation error
}

Can you explain why this is happening?

like image 242
Shruti Rawat Avatar asked Dec 03 '22 22:12

Shruti Rawat


2 Answers

The reason is specified in JLS 5.1.2: It says that : long to float or double is a widening conversion.
Whereas, float to byte, short, char, int, or long is narrowing conversion.
That's why
float b=a; is working fine in your program , since it is widening conversion.
And long c=b; is showing compilation error since it is a narrowing conversion.

like image 94
Mac Avatar answered Apr 26 '23 23:04

Mac


When you convert from an integral type to a floating point one, it is always clear what you want to do: you change number's representation, but you keep the same number.

Converting from floating point to integral types, on the other hand, has some ambiguity: it is not clear what you would like to do with the fractional part. You may want to

  • Truncate the fractional part,
  • Perform mathematical rounding, or
  • Round the number up.

That's why the language asks you to be specific about what you want to do when converting floating-point numbers to integral types.

like image 42
Sergey Kalinichenko Avatar answered Apr 26 '23 23:04

Sergey Kalinichenko