*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Primitive Data type Simple Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Primitive Data type Simple Problem" Watch "Primitive Data type Simple Problem" New topic
Author

Primitive Data type Simple Problem

Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
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 ???


SCJP 6.0 96%

(Connecting the Dots ....)
Tayitu Betule
Ranch Hand

Joined: Dec 18, 2009
Posts: 39
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

Joined: Jan 09, 2008
Posts: 525
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 ... ...

BEE MBA PMP SCJP-6
Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
@ 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

Joined: Jan 09, 2008
Posts: 525
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

Joined: Dec 18, 2009
Posts: 39
Thank you for correcting on the casting part.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Primitive Data type Simple Problem