Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why explicit type casting required from double to float but not from int to byte?

Tags:

java

casting

Consider following statement:

byte by = 5; //works fine

literal '5' is of type int and small enough to fit into a variable of type byte. Compiler does the implicit type casting here (from int to byte).

Now consider following scenario:

float fl = 5.5;    //compilation error

literal '5.5' is of type double, also small enough to fit into a variable of type float. Why do we need to explicitly type cast like this:

float fl = (float) 5.5;   //works fine

Why compiler is not doing the casting for us in case of floating points?

like image 486
maximus335 Avatar asked Feb 06 '15 08:02

maximus335


People also ask

Can a float value be assigned to a double variable without type casting?

Now to convert double to float you need to cast while assigning double data to double type cast is not required.

What is type casting why it is required in programming?

Type casting is the process in which the compiler automatically converts one data type in a program to another one. Type conversion is another name for type casting. For instance, if a programmer wants to store a long variable value into some simple integer in a program, then they can type cast this long into the int.

What is the problem with type casting in Java?

In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into lower data types (having smaller size). Hence there is the loss of data. This is why this type of conversion does not happen automatically. Note: This is also known as Explicit Type Casting.

What is type casting in Java why it is required?

Type casting is when you assign a value of one primitive data type to another type.


1 Answers

In the integer version, the compiler knows that all the data in the number 5 can be stored in a byte. No information is lost. That's not always true for floating point values. For example, 0.1f isn't equal to 0.1d.

Now for the example, you've given, the decimal value 5.5 is exactly represented in both float and double, so you could argue that in that case, no information is lost - but it would be pretty odd for the language specification to have to make this valid:

float f = 5.5;

but this invalid:

float f = 5.6;

The language specification is happy to talk about whether a number fits within the range of float/double (although even that isn't as simple as you might expect) but when it comes to whether a literal can be exactly represented, I don't think it ever goes into detail.

like image 110
Jon Skeet Avatar answered Sep 18 '22 22:09

Jon Skeet