• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

byte  RSS feed

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Why does the follow code result 1.
byte b = 0;
b += 1;
But the follow code need a cast?
byte a=0;
byte b=1;
byte c = (byte)(a+b);
Thank you.
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Expression b += 1; is evaluated as
b = (byte)(b +1);
Hence it does not complain, as the cast is put for you by the compiler.
In your second code snippet.
byte c = (a+b);
Both a and b are promoted to int (numeric binary promotion) so the expression becomes
c = (int)a + (int)b;
If you do not cast it to byte, it becomes an error since you are trying to store int value in byte variable (i.e c)
-Sandeep Nachane
www.tipsmart.com

[This message has been edited by Sandeep Nachane (edited July 13, 2001).]
 
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!