• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arithmetic operators

 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! Quoting from "The Complete Java2 Certification Study Guide":
Unary + has no effect on the value of its operand, but the expression is promoted to at least int.
End quote.
When I tried this code out, it gave me a compile time error.
byte x;
x = +2;
x = 128;
Is x still a byte or has it been promoted to an int as the book says? Help!
Any replies will be much appreciated.
Gaia.
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, x isn't an operand here, so it wouldn't be promoted. If you do something like

Then you get a loss of precision error at x = +y; because the value in y is now promoted to an int. However, what I'm not sure of is why doing x = +2; doesn't give the same error since you would think 2 would be considered an int and therefore unable to go into the byte without a cast.
Also, with doing the code above, y does not become an int, it is still of type byte, but the value returned from +y is considered an int.
Jason
[This message has been edited by jason adam (edited November 20, 2001).]
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


[This message has been edited by Marilyn deQueiroz (edited November 21, 2001).]
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But why does x = +2; work?? Is +2 not considered an int here, since the unary op. promotes to at least an int? Or does that not apply with a constant?
Jason
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jason,
I would say that the compiler knows that +2 can be replaced by 2 which is handled under the special case of an integer literal.
Regards,
Manfred.
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Thank you for all your replies.
Found this in Chapter Four (of the same book):
Quote:
... Java relaxes its assignment conversion rule when a literal int value is assigned to a narrower primitive type (byte, short, or char) provided the literal value falls within the legal range of the primitive type.
End quote.
So, I guess this is why
byte x = +2;
is allowed.
+2, which is an int literal value, has a magnitude that falls within the legal range of the byte primitive data type.
Thanks again.
Gaia.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic