This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "type conversion" Watch "type conversion" New topic
Author

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

srikanth


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.
Thanks
 
 
subject: type conversion
 
Similar Threads
primitive conversion and assignment
alleged lost of precision
Its the hairy ++ again.
primitive conversion
short to byte