compound-assignment operator and type casting

We’ve been learning since we first printed “hello world” that

i += 1

expands to

i = i + 1

Well, here’s a little problem to shake the faith.

byte i = 1;

i  = i + 1;

System.out.println(i);

Being java programmers worth our salt, it wouldnt take much to identify the compilation error.

Error: Possible loss of precision

So how do we explain that the next code snippet prints the value 2?

byte i =1;

i += 1;

System.out.println(i);

Here’s the secret: i += 1 is not same as i = i + 1

When you do an assignment (the first code snippet), java enforces type checking because the LHS and RHS may very well be independent of each other.

But the compound-operator is more like an incremental operator. The += modifies the value of the variable involved, rather than assigning a new value to the variable. When you modify a byte, you expect a byte as the result. To make life easier, java does an implicit type conversion for compound-operators because they are modifiers.

Have fun!

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: