• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conversion

 
Venkatesh Gowri
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, i have a doubt regarding implicit conversion
in this example.
byte b=2,b1=3;
b=b*b1;
Why does this result in a compliation error.
If both the operands are bytes why is it necessary to convert it to an int to carry out the * operation.
Thanks in advance
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Venkatesh Gowri:
Hey, i have a doubt regarding implicit conversion
in this example.
byte b=2,b1=3;
b=b*b1;
Why does this result in a compliation error.
If both the operands are bytes why is it necessary to convert it to an int to carry out the * operation.
Thanks in advance

Try the following
byte b=2,b1=3;
b*=b1;
The compound assignment operator includes an implicit cast to the type of the left operand. However, the simple assignment operator that was used in your example has no such implicit cast.
If both operands of the multiplication operator can be converted to type int, then the result of the expression is of type int. If you want to assign the result to a variable of type byte using the simple assignment operator, then it must be cast to type byte.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Language Specification, Section 5.6.2, Binary Numeric Promotionshould answer your questions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic