hi guys, Given these declarations, which of the following expressions are valid?
byte b = 1; char c = 1; short s = 1; int i = 1;
Select the three correct answers.
a. s = b * 2;
b. i = b << s;
c. b <<= s;
d. c = c + b;
e. s += i;
i got this questtion from Khalid book.. i have some doubt in this question ... answers for this question are b,c,e. i agree with b...for obvious reasons that int is larger than short in size. for c & e my doubt is if this byte a = 10, b = 20, c = 0; c = a+b; gives a compiler error ..saying that there will be loss of precision .. & the solution is we have to cast it to byte. how come we dont need a cast here for s += i which is s = s + i & b <<= s which is b = b << s ;
can anybody PLS help me with this ..
Only those who will risk going too far, Can possibly find out how far one can go! <br />happiness is journey and not destination<br /> <br />A Nayak<br />----------------------------------<br />SCJP 1.4<br />SCWCD 1.3<br />SCBCD 1.3
The compiler will implicitly do a narrowing conversion for an assignment statement if the right hand operand is a compile time constant of type byte, short, char, or int and the value falls within the range of the variable on the left and if the variable is of type byte, short, or char.
This was in Dan's Mock exam 1 Q22
If both operands of a binary arithmetic expression are of type byte, char or short; then both are implicitly widened to type int, and the result of the expression is of type int.
This is from Dan's Mock exam 2 Q11
With these two rules...All the 5 answer choices should be correct. However they are not. Could someone please explain !!
a. s = b * 2; b. i = b << s; c. b <<= s; d. c = c + b; e. s += i;
a & d - As Murtuza correctly posted, operands of numeric expressions are promoted to at least int. So a and d are invalid, as we cannot assign an int value to a short or char variables without an explicit cast. b - This answer is valid because the result of the shift expression is an int, the same type of variable i. c & e - These answers are valid because all the compound assignment operators do an implicit cast. So, b <<= s is the same as b = (byte)(b << s) and s += i is the same as s = (short) (s + i).
Hope this helps. Stefan [ August 16, 2004: Message edited by: Stefan Guilhen ]