File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Primitive Data type Simple Problem

 
Sahil Kapoor
Ranch Hand
Posts: 316
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte a =2;
byte b= 3;

byte c= a+b; // Compiler error ???

Problem:- Why Compiler error , i have declared c to be of type byte and a and b are already byte.

Similar is the case for short also. Please do explain ???
 
Tayitu Betule
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Sahil,

When you've + operator, the value added will resolve to an int type not byte. So you either have to declare c as an int or cast the result to byte as in (byte)a+b. Try it.

Hope this helps.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not exactly the + operator, but rather that all operands in an expression
are promoted to at least type int before the operation is done. The same
error occurs if you assign (long + byte) to an int.

Jim ... ...
 
Sahil Kapoor
Ranch Hand
Posts: 316
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Tayitu Betule

Thanks Sir, but i just want to add a bit correction

(byte) a+b would not work.

(byte) (a+b) would work !!!

Thanks
Cheers!!!
 
Jim Hoglund
Ranch Hand
Posts: 525
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, because the casting operation takes precedence over the + operator. With
((byte) a + b), only a is cast to byte. Then both a and b are promoted to int before
the add. The result must be explecitly downcast to be considered a byte (or short).

Jim ... ...
 
Tayitu Betule
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for correcting on the casting part.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic