15

A colleague of mine asked this question to me and I am kind of confused.

int i = 123456;
short x = 12;

The statement

x += i;

Compiles fine however

x = x + i;

doesn't

What is Java doing here?

3
  • You are trying to add int to short however. a = b != b = a Commented Sep 21, 2012 at 20:25
  • You are actually adding an int to a short Commented Sep 21, 2012 at 23:17
  • 3
    For interest try this char ch = '0'; ch *= 1.2; now ch is '8' ;) Commented Sep 22, 2012 at 6:38

3 Answers 3

20
int i = 123456;
short x = 12;
x += i;

is actually

int i = 123456;
short x = 12;
x = (short)(x + i);

Whereas x = x + i is simply x = x + i. It does not automatically cast as a short and hence causes the error (x + i is of type int).


A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

- JLS §15.26.2

Sign up to request clarification or add additional context in comments.

Comments

4

The + operator of integral types (int, short, char and byte) always returns an int as result.

You can see that with this code:

//char x = 0;
//short x = 0;
//byte x = 0;
int x = 0;
x = x + x;

It won't compile unless x is an int.

Comments

2

Numbers are treated as int unless you specifically cast them otherwise. So in the second statement when you use a literal number instead of a variable, it doesn't automatically cast it to the appropriate type.

x = x + (short)1;

...should work.

2 Comments

I wrote wrong equation. I updated my question. See its x = x + i.
Ok, then why doesn't x = x + x; work? The problem isn`t on the number 1 but on the + operator that returns an int.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.