• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan Chisholm's mock exam question

 
Moya Green
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<<= 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
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic