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 type conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "type conversion" Watch "type conversion" New topic

type conversion

sandeep dhingra
Ranch Hand

Joined: Jul 30, 2005
Posts: 41
can some one plz help me
look at this
byte b=2;
b += 10; //1
b = b+10; //2

1. works fine but 2. does not.

i know that we have to explicitly narrow the conversion in 2. by adding byte on RHS but but how come 1. works as both are one and the same thing.
Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

hi sandeep,

byte b=2;
b += 10; //1
b = b+10; //2

1 and 2 are not same thing.
1 is identical to b=(byte) b+10; works fine.
2 does not compile because b is converted to int (due to + operator) and after adding 10, the result(int) can not be assigned to byte value.
srikanth reddy
Ranch Hand

Joined: Jul 28, 2005
Posts: 252
hi Areca ...
b=(byte)b+10;wont work ...will give loss of precision ...i think u mean to say b=(byte)(b+10)..this will work fine .....

thanks & regards


Thanks & Regards<br /> <br />-Srikanth
Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

ha, i meaned b=(byte)(b+10) you are right.
I agree. Here's the link:
subject: type conversion
Similar Threads
short to byte
alleged lost of precision
Its the hairy ++ again.
primitive conversion and assignment
primitive conversion