• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
usha prithvi
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • 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
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • 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 ]
 
vivek parepalli
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thankz for the explanation!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic