Question 7 class K { public static void main (String[] s) { byte b = 127; b <<= 2; System.out.println(b); } }
What is the result of attempting to compile and run the above program? ans. Prints: -4 My question is: why the type of b is remained as byte, not promoted to int? Thanks a bunch! -Moya
Ashish Hareet
Ranch Hand
Joined: Jul 14, 2001
Posts: 375
posted
0
<<= is called an extended assignment operator & when such an operator is used there is an implicit narrowing of the result i.e. the result is automatically cast back to the destination type. Here's how b <<= 2 is evaluated - b = (byte)(127 << 2) If the expression were - b = b << 2 instead of b <<= 2 you'd get a compiler error. Ashish H.
Moya Green
Ranch Hand
Joined: Jan 24, 2002
Posts: 49
posted
0
Dear Ashish, Thank you very much! I am going to try your VoodooExam soon. I hope your mock exam has an html or text version. That's just my personal opinion. I understand you might have your concern. Anyway, thanks for your help. Moya
Ashish Hareet
Ranch Hand
Joined: Jul 14, 2001
Posts: 375
posted
0
I hope your mock exam has an html or text version.
Sorry Moya but as soon as a HTML version is available you'll be the first to know . Thanx for the tip - an HTML version would have it's advantages. Ashish H.