File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting 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 "casting" Watch "casting" New topic


usha prithvi
Ranch Hand

Joined: Jun 22, 2005
Posts: 31

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

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

byte b1 = 33;
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.

Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
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 ]

Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
vivek parepalli

Joined: Jul 16, 2004
Posts: 9
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



usha prithvi
Ranch Hand

Joined: Jun 22, 2005
Posts: 31
Thankz for the explanation!
I agree. Here's the link:
subject: casting
It's not a secret anymore!