This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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.
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).]
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.
Joined: Aug 01, 2001
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.