Momen Travolta wrote:
Do I have to use casting only when assigning a higher data type to a lower one?
Casting must be explicit if the source range is not within the target range. This means that an double must be explicited casted to a long, but not vica versa. And in the case of a short and char, it means that casting must be done in both directions.
Long.MAX_VALUE is 2^63-1, or 9223372036854775807. Both a and b are larger than this number. c is shorter but the number is an int, and is larger than Integer.MAX_VALUE (2^31-1 or 2147483647). Adding the L tells the compiler that this literal is not an int but a long.
Line 1: You are dividing a float with an int. The result will be a float. Floats are limited to about 6 or 7 digits of precision.
Line 2: You are dividing a long by an int. The result will be a long. Because it is an integer division, the result is 0.
Line 3: Similar to line 2, integer division, result is 0.
Line 4: Dividing a double by an int, the result is a double, which has more digits than a float (line 1).
Line 7: Floating-point literals are double by default, you can't assign them to a float without casting or appending an "f".
Lines 8-9: Assigning values to float, what are you unclear about here?
Line 10: Assigning an int literal to a float is allowed, you might loose some digits.
Line 14: The int literal is too big to fit into a 32-bit int, so you get an error.
Line 15: The long literal is too bit to fit into a 64-bit long, so you get an error.
Line 16: The int literal is too big to fit into a 32-bit int, so you get an error.