• Post Reply Bookmark Topic Watch Topic
  • New Topic

casting int to Byte  RSS feed

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
i have doubt regarding one question mentioned below:

Given:

byte b=3;
byte c=7;


Which of the following statements will not compile?

1. c=b+c;

2. c=+b;

3. c+=b;

4. c=-b;

out of these 1,2 and 4 require explicit casting to byte, but 3 one is fine. i'm not able to understand why third one is fine, because c+=b means
c = c+b which should convert bytes to int first..

please clear my doubt how compiler interprets c+=b operation.

 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
c += b does not mean exactly c = c + b; it actually means c = (byte) (c + b) . The assignment operators always include this implied cast to the type of the left operand.
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ernest,
you mean to say that compiler itself converts b += c to
b = (byte)b + c.

or it happens at runtime.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!