Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# unary operator and primitive size

chafule razgul
Ranch Hand

Joined: Feb 09, 2002
Posts: 63
I've accepted the following as is but would love a good explanation
byte b = 2;
b = b+1; //naturally fails to compile
b+=1; //compiles fine.. why oh why..
Rick Salsa
Ranch Hand

Joined: Jul 17, 2001
Posts: 173
Hi Cahfule,
b = b+1 doesn't complie because b gets promoted to an int, so an int can not be implicitly converted to a byte.
The easist way to think of the last expression is this:
b = (byte) ((int)b + 1);
This will be done behind the scenes for you. To get the first one to compile, you would need to explicitly cast it to a byte:
b = (byte) (b+1);
Hope that helps,
/rick
[ February 21, 2002: Message edited by: rick salsa ]
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4242

2

With the compound assignment operators, there is an implied cast to the type of the left hand side. That is, the expression
b += 1;
will be compiled as
b = (byte)(b + 1);

Here's the relevant section in the JLS: http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304
Junilu
Jennifer Wallace
Ranch Hand

Joined: Nov 30, 2001
Posts: 102
And, because implicit compiler casting is involved in compound operators huge numbers will also work!
byte b=1000; // Compiler error,out of range
But,
byte b=0;
b+=1000; // works fine though b has some
truncated value not 1000
[ February 22, 2002: Message edited by: Jennifer Wallace ]

I agree. Here's the link: http://aspose.com/file-tools

subject: unary operator and primitive size