Difference between a+=b and a=a+b in Java [duplicate] - java

This question already has answers here:
Difference between a += 10 and a = a + 10 in java? [duplicate]
(5 answers)
Closed 8 years ago.
I've been told that there are differences between a+=b; and a=a+b; which can result in only one of those being legal depending on the type declerations.
Does anyone have an example of this?

There is basically no difference, however there is a subtle difference.
The arithmetic assignment operators do an implicit cast. e.g.
byte a = 1;
int b = 2;
a += b; // compiles
a = a + b; // doesn't compile as a byte + int = int
a = (byte) (a + b); // compiles as this is the same as +=
For more weird examples.
int a = 5;
a += 1.5f;
// a == 6
char ch = '0'; // (char) 49
ch *= 1.1; // ch = '4';
long l = Integer.MAX_VALUE;
l += 0.0f; // i = (long ) ((long ) l + 0.0f)
// i == Integer.MAX_VALUE + 1L; WTF!?
// l is no longer Integer.MAX_VALUE due to rounding error.

The JLS (section 15.26.2) says:
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.
The presence of the type-cast means that there are a couple of edge cases where a = a op b means something different to a op= b.
See Peter Lawrey's answer for one example. It is when a is a byte and b is an int and the "op" is +. The "gotcha" is a + b produces an int, which then can't be assigned to a ... without a typecast.
The same scenario applies with other types for a and b and for other arithmentic and bitwise operators.

int a = 10;
int b = 20;
a=a+b; // 30
a+=b; // 30
System.out.println(a);
Both will give the same answer.

Related

Unexpected output in Java while adding of two Integers [duplicate]

This question already has answers here:
How can I detect integer overflow on 32 bits int?
(5 answers)
Closed 2 years ago.
I am new in java language, here is m not able to understand, why program returning -2 after adding two full range integers.
class Variables {
public static void main(String[] args) {
int a = 2147483647;
int b = 2147483647;
long c = a + b;
System.out.println( c );
}
}
I am expacting 4294967294 value in my variable c, but why it returns -2
please explain me the reason behind this
You reach Integer.MAX_VALUE so you're going to -2147483648, then adding Integer.MAX_VALUE again will result in -2
To get 4294967294, you need to cast one value as long before to do a long sum and not an int one
int a = 2147483647;
System.out.println(a + 1); //-2147483648
int b = 2147483647;
System.out.println(a + b); // -2
long c = a + (long) b; // or ((long) a) + b;
System.out.println(c); //4294967294
The result of adding two ints is an int, which of course overflows when you add a and b. Only then is it promoted to a long.
You can get the result you expected by casting one of them to long before performing the addition:
long c = ((long) a) + b;

how does shorthand operator in java works different from normal operator? [duplicate]

This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 5 years ago.
i know that by default numbers are stored as integer in java but
byte x = 10;
x = x + 10;
is giving error while
byte x = 10;
x += 10;
is compiling fine
JLS have an answer for you
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.
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
So in your case your second statement equlas to
x = (byte) x + 10;
That is the reason compiler is happy about.

compound assignment operator in java [duplicate]

This question already has an answer here:
Order of operations for compound assignment operators in Java
(1 answer)
Closed 6 years ago.
int a = 2;
int b = 3;
int c = 10;
a +=(a += b) + c; // this will be same as --> a = a+((a= a+b) +c);
/* 2+((2=2+3)+10)
after adding 2+3
now value a = 5;
5 +((5)+10)
5 + (15)
a = 20
*/
System.out.println("a: "+a); // a:17
when i execute above program the answer is a:17 why not a:20 ?
according to me.
After resolving (a += b) now the value of a should be 5 then (a += b) + c would be 15 and after that a +=(a += b) + c; should be 20
please help me understand thanks.
The compound assignment operator stores the original value of the left operand before evaluating the second operand and performing the compound assignment (addition + assignment in this example).
Therefore
a += (a += b) + c;
is equivalent to :
int temp = a;
a = temp + (a += b) + c;
2 + 2 + 3 + 10 = 17
This is a good example of where order of evaluation and precedence don't match. They usually do which makes it confusing when there is a difference, as you mention the expression is evaluated left to right like this
int s = a; // stack
int t = a + b; // second stack value.
s += t;
s += c;
a = t;
a = s;
Note the (a+=b) is the same as (a+b) in this case.
In Java, you can replace a += b with a = a + b. And that is very important.
Hence your expression is equivalent to
a = a + (a = a + b) + c
Note that this will be evaluated as a = Term1 + Term2 + Term3 and in the order left to right.
Term1 is 2.
Term2 is the only tricky one. It is 5 (and has the side-effect of increasing a to 5 but that gets clobbered by the eventual assignment).
Term3 is 10.
That recovers the total, 17.
Note that the behaviour of this expression in C and C++ is undefined.
It is a bit tricky to understand. Although you have a += b on the right-hand side, that doesn't change the value of a that's used for the += at the beginning of the expression; that will still be 2. E.g.:
a += (a += b) + c;
a = 2 + (a[still 2] += 3) + 10
a = 2 + (5) + 10
a = 17
The a += b on the right-hand side is really just a a + b, since this is all on the right-hand side of a += already directed at a.
Details in JLS§15.26.2: Compound Assignment Operators.
First you do a+=b so 2+3 you have 5. Then a+= your answer (here 5) so 2+=5 = 7. Then 7+10 = 17

Java Puzzler - casting a double to int

int anInt = 1;
double aDouble = 2.5;
anInt = anInt + aDouble; // Error - need to cast double to int
anInt += aDouble; // This is ok. Why?
anInt = aDouble; // This is also an error.
anInt = 1 + aDouble; // This is also an error.
So my questions is: Why is it not a compile error to do anInt += aDouble?
Three of the four cases properly report an error. Compound assignment is the only exception from the rule. Java Language Specification, part 15.26.2, explains why:
15.26.2 Compound Assignment Operators
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.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
As you can see, the error is avoided by implicit insertion of a cast.

Primitives float and double: why does f+=d not result in Type Mismatch Error? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java += operator
Code example:
double d = 1;
float f = 2;
f += d; // no error?
f = f+d; // type mismatch error, should be f = (float) (f+d);
So why does f+=d not produce an error (not even at runtime), although this would decrease the accuracy of d?
As per JLS 15.26.2
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.
That means:
f += d;
would become as
f = (float) (f+d);
The compount assignment does an implicit cast.
a #= b;
is equivalent to
a = (cast to type of a) (a # b);
Another example
char ch = '0';
ch *= 1.1; // same as ch = (char)(ch * 1.1);
// ch is now '4'

Categories