Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why do I need casting in some instances in java but not in other ones? For e.g I do not need to cast the expression byte i = 4 * 5 but I need to cast the expression byte r = i * 5. Why is this the case?

What I have tried:

I wrote a java program where I tried it
Posted
Updated 20-Jan-17 0:05am

Because the compiler "knows" the value of 4 * 5 will fit in a byte, so it can treat it as a byte value. When you try to multiply an integer by a constant the result will be an integer - and a conversion to byte will potentially lose information (since a byte can only hold 8 bits, and an integer is typically 32 bits).
To avoid the loss of data, it warns you that you need an explicit cast.
 
Share this answer
 
Because in the right side of
Java
byte i = 4 * 5;
there is a constat expression, evaluated at 'compile time' and so is is know in advance it fits in a byte.

On the other hand, on the right side of
Java
byte r = i * 5.

there is a variable, so it cannot be avaluated at 'compile time', automatic type promotion happens (see Automatic Type Promotion in Expressions[^]) and you need a cast.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900