Submitted by c-admin on Tue, 06/04/2019 - 00:36
Question:
Which of these assignments are valid?
Select 3 options
A. short s = 12 ;
B. long g = 012 ;
C. int i = (int) false;
D. float f = -123;
E. float d = 0 * 1.5;
Answer and Explanation (Click to expand) Answer:
A - This is valid since 12 can fit into a short and an implicit narrowing conversion can occur.
B - 012 is a valid octal number.
D - Implicit widening conversion will occur in this case.
Explanation:
Note that float d = 0 * 1.5f; and float d = 0 * (float)1.5 ; are OK
A narrowing primitive conversion may be used if all of the following conditions are satisfied:
1. The expression is a constant expression of type int.
2. The type of the variable is byte, short, or char.
3. The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
Note that narrowing conversion does not apply to long or double. So, char ch = 30L; will fail even though 30 is representable in char.