aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes compound assignment operator behaving differently for Byte and byte 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 "compound assignment operator behaving differently for Byte and byte" Watch "compound assignment operator behaving differently for Byte and byte" New topic
Author

compound assignment operator behaving differently for Byte and byte

Rachid Aourich
Greenhorn

Joined: Apr 03, 2011
Posts: 16

hi,

i can't understand why there is a compilation error in Demo2 , however it is not in Demo1 ?! can you please explain it

Dan Drillich
Ranch Hand

Joined: Jul 09, 2001
Posts: 1174
Demo2 is just fine. It runs and prints 20.

Regards,
Dan


William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

Demo2 doesn't compile for me. It says inconvertible types int and Byte. This is really interesting as in case of primitive byte it works fine. The answer is hidden here I believe.
A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is :

* Byte and the value of the constant expression is representable in the type byte.
* Short and the value of the constant expression is representable in the type short.
* Character and the value of the constant expression is representable in the type char.

In your example when you use compound assignment operator, the resulting value cannot be automatically narrowed from int to byte thus its not boxed. I might be wrong though ...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Pramod Kankure
Greenhorn

Joined: Oct 25, 2011
Posts: 6
Demo2 does not compile as you are using a wrapper class Byte of smaller primitive size to hold the integer result generated by compound assignment.
In case of Demo2 following things happen

1) b is unboxed from Byte wrapper to byte and then incremented by 10
2) The result is to be narrowed down to byte
3) The result is to be boxed back to Byte wrapper.



JAVA does not support boxing of a result that is narrowed down. You can use a bigger wrapper like Long or Integer and can still use compound operator .

In case of Demo1, JAVA does not have to box back a result at all as it is assigned to a byte primitive type.
Dan Drillich
Ranch Hand

Joined: Jul 09, 2001
Posts: 1174
Really interesting as from within Eclipse that uses jdk 1.5 it compiles and runs fine but compilation fails in the command line.

Does it make sense?

Regards,
Dan
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: compound assignment operator behaving differently for Byte and byte