• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Primitive Data type Simple Problem

 
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ???
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for correcting on the casting part.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic