• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

casting

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,

have a look at the below code......

class A{
Static void main(String args[]){

byte b1 = 33;
b1++;
byte b2 = 55;
b2 = b1 + 1;// 1
System.out.println(b1 + " " +b2);
}
}

In the above code compilation error is occuring at line 1. Says cant cast from int to byte. I know that byte values range from -128 to 127. Then why b1 value is not accepted as byte.what is the error? am i missing any point in casting.please explain.

Thankz
 
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's because any arithmetic operations will atleast result in an integer.

Ex : -
1. byte + byte = int
2. int + byte = int
3. float + int = float

Also in this line b2 = b1 + 1

At run time there is a possibility that b1 is greater than 127, so it's greater than the size of byte & hence the compiler throws error. Explicit cast is required here.
[ July 09, 2005: Message edited by: Srinivasa Raghavan ]
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As said by Mr. Srininvas. Guess you know about the type promotions in the Arithmetic Expressions. Here at //1 1 is being considered as integer. So the error. You can try either

b2=(byte)(b1+1);

or

b2=b1+(byte)1;
 
usha prithvi
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thankz for the explanation!
 
What could go wrong in a swell place like "The Evil Eye"? Or with this tiny ad?
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic