• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compound assignment operator behaving differently for Byte and byte

 
Rachid Aourich
Greenhorn
Posts: 16
Hibernate Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Demo2 is just fine. It runs and prints 20.

Regards,
Dan
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ...
 
Pramod Kankure
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic