I've misplaced += with =+ one too many times, and I think I keep forgetting because I don't know the difference between these two, only that one gives me the value I expect it to, and the other does not.
Why is this?
a += b is short-hand for a = a + b (though note that the expression a will only be evaluated once.)
a =+ b is a = (+b), i.e. assigning the unary + of b to a.
Examples:
int a = 15;
int b = -5;
a += b; // a is now 10
a =+ b; // a is now -5
+= is a compound assignment operator - it adds the RHS operand to the existing value of the LHS operand.
=+ is just the assignment operator followed by the unary + operator. It sets the value of the LHS operand to the value of the RHS operand:
int x = 10;
x += 10; // x = x + 10; i.e. x = 20
x =+ 5; // Equivalent to x = +5, so x = 5.
+= → Add the right side to the left
=+ → Don't use this. Set the left to the right side.
a += b equals a = a + b. a =+ b equals a = (+b).
x += y
is the same as
x = x + y
and
x =+ y
is wrong but could be interpreted as
x = 0 + y
It's simple.
x += 1 is the same as x = x + 1 while
x =+ 1 will make x have the value of (positive) one
Some historical perspective: Java inherited the += and similar operators from C. In very early versions of C (mid 1970s), the compound assignment operators had the "=" on the left, so
x =- 3;
was equivalent to
x = x - 3;
(except that x is only evaluated once).
This caused confusion, because
x=-1;
would decrement x rather than assigning the value -1 to it, so the syntax was changed (avoiding the horror of having to surround operators with blanks: x = -1;).
(I used -= and =- in the examples because early C didn't have the unary + operator.)
Fortunately, Java was invented long after C changed to the current syntax, so it never had this particular problem.
Because =+ is not a Java operator.
Related
int a = 1;
a -= a + a;
The above code result is -1, which I am expecting it to be 1.
But the below code actually get me 1
a = a - a + a
Aren't they supposed to be the same? How the first code get to -1?
I tried to look at mathematical order of operation of addition and subtraction, which I thought I would have misunderstanding on how they works. But it looks like I am correct by doing left to right operation on the calculation.
The Java Language Specification writes:
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 is, the expression
a -= a + a
is equivalent to
a = (int) ((a) - (a + a))
which evaluates like
a = (1) - (1 + 1)
-= has lower precedence than +, so the order of operations is:
a -= (a + a);
a -= (1 + 1);
a -= 2;
On the other hand, - has the same precedence as +, and is left-associative, so the order of operations here is:
a = ((a - a) + a);
a = ((1 - 1) + 1);
a = ( 0 + 1);
a = 1;
It makes sense that the answer is -1 since a -= a+a means you are setting the variable a to the value of a-(a+a). Since a is initialized as 1, a-(a+a)=1-(1+1)=1-2=-1.
Order of operations - in the first one, a + a is calculated then that is subtracted from a. In the second one, the subtraction of a from a is done, then the addition (left to right).
This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 3 years ago.
I got these 2 different codes in Java that I can't understand how they produce these specific outputs.
They seemed to work in 2 different logic and I can't figure it out!
int a = 5;
int b = 4;
a -= (b++) + ++a; // For more confusing results replace -= with += and see how the logic changes.
System.out.println(a); // Output: -5
and
int c = 8;
c += ++c;
System.out.println(++c); // Output: 18
How does each situation work and how are they producing these specific outputs?
The major difference here is what post and pre increment are. These determine whether the value is increased before evaluation, or afterward.
Here is how the first case breaks down mathematically:
a = 5 - (4 + 6), which reduces to -5.
Note that a is increased from ++a AKA preincrement before the math is done, however b is calculated as 4. Another thing to note is the a used from the -= uses the original a value, regardless of post or pre increment.
The second equation reduces to this mathematically:
c = 8 + 9 which reduces to 17.
The output prints 18 because your System.out.print(++c) increments it one more time before output due it being preincrement. Note if the print statement used c++, the value would print to 17.
The chart for operator precedence can be found here. Note that assignment has lower precedence than the unary/postfix operators.
It's all about the Operator Precedence in Java. Check that table and figure out which operation takes place first and which last.
It is equivalent to:
int a = 5;
int b = 4;
a -= (b++) + ++a; // => 5 -= (4) + 6
int c = 8;
c += ++c; // => 9 += 9
The main diff is thet:
++a and ++c increments the value and immediately returns it.
b++ returns the value and then increments it.
There is a difference in the order of ++. While both increase the variable, ++a will pass the original value to the operation chain your in middle of; while a++ would pass the new value. So for your first example:
++a --> a is now 6; but the equation is using 5:
a -= (b++) + 5;
b++ --> b is now 5;
a -= 5 + 5;
a -= 10;
? = 5 - 10;
a = a - 5 + 5;
a = 5 - 5 + 5;
a = -10;
(You should have enough to trace the second example).
For a list of operations try this. Some more increment examples are here.
A minimal example is `
int x=3,y=3;
x += ++x;
y+= y++;
at the x x is 7 and y is 6. Precedence alone is not enough to explain the behaviour. Using precedence the second line would be x += (++x), i.e. increment x and return its value, (x is now 4); next we have x+=4 which would return 8.
Instead, it seems better to treat x += w as a short hand for x = x + w, this rewriting happens before evaluation. In our case the rewriting is x = x + ++x interpreted as x = (x + (++x)). So interpreted as
x = ( 3 + (++x))
x = ( 3 + 4 ) x is 4
x = 7 x is 7
A simlar system works to the y equation giving y = 6 at the end.
I read a few post regarding unary operator:
What is the Difference between postfix and unary and additive in java
"C - C++" joke about postfix/prefix operation ordering
And a few more.
However, I still don't understand exactly when the value is changed.
For example:
int x = 1;
x = x++;
System.out.print("x = x++ ==> ");
System.out.print(" x = " + x);
System.out.println();
int x = 1;
x = x++ + x++;
System.out.print("x = x++ + x++ ==> ");
System.out.print(" x = " + x);
System.out.println();
The output is:
x = x++ ==> x = 1
x = x++ + x++ ==> x = 3
So in the first block x is assigned to x and afterwards incremented, but the value is never used, otherwise the output would have been x = 2.
In the second block, if I understand correctly, the first x++ is evaluated before the assignment and the second x++ is evaluated afterwards but is never used.
If in the second block both x++ would have been evaluated after the assignment but never used, the output would have been x = 2. If both have been used, the output would have been x = 4.
My IDE also indicated that the first x++ is used, but the second is not used:
So to conclude - I'm still confused about when and how exactly the increment is done.
At the line
x = x++ + x++;
Assuming x = 1, the first x++ returns "1" as the value, and then it increments x to 2. So basically, it's assigning the old value back to x.
The second x++ does the same; it returns the value of x, which is now 2, and only then increments its value to 3 - that value, is not used.
Your code is equivalent to:
tmp = x;
x = x + 1;
tmp2 = x;
x = x + 1; // not used
x = tmp + tmp2;
Links that may help you:
JSL - 15.14.2. Postfix Increment Operator ++
JLS - 15.15.1. Prefix Increment Operator ++
What is x after “x = x++”?
I came across this problem in this website, and tried it in Eclipse but couldn't understand how exactly they are evaluated.
int x = 3, y = 7, z = 4;
x += x++ * x++ * x++; // gives x = 63
System.out.println(x);
y = y * y++;
System.out.println(y); // gives y = 49
z = z++ + z;
System.out.println(z); // gives z = 9
According to a comment in the website, x += x++ * x++ * x++ resolves to x = x+((x+2)*(x+1)*x) which turns out to be true. I think I am missing something about this operator precedence.
Java evaluates expressions left to right & according to their precedence.
int x = 3, y = 7, z = 4;
x (3) += x++ (3) * x++ (4) * x++ (5); // gives x = 63
System.out.println(x);
y = y (7) * y++ (7);
System.out.println(y); // gives y = 49
z = z++ (4) + z (5);
System.out.println(z); // gives z = 9
Postfix increment operator only increments the variable after the variable is used/returned. All seems correct.
This is pseudocode for the postfix increment operator:
int x = 5;
int temp = x;
x += 1;
return temp;
From JLS 15.14.2 (reference):
The value of the postfix increment expression is the value of the variable before the new value is stored.
Nothing to do with operator precedence per se, just the order of evaluation.
Two things to know here:
x++ is the postfix increment, so the value of x is incremented after it is evaluated
* evaluates the right side then the left side.
Considering point 2, the expression x++ * x++ * x++ can be rewritten more specifically as x++ * (x++ * (x++)).
The whole expression can be written as the procedures:
a = x
x += 1
b = x
x += 1
c = a*b
d = x
x += 1
return c*d
The postfix operator x++ means something like "give me the value of x now, but increment it for future references"
So, by the order of operations and evaluation,
x++ * x++ * x++
is interpreted first as
3 * 4 * 5 (=60)
Which is then added to the original 3, yielding 63.
The original value is used because it's on the same line, had you written something like:
int x = 3;
int y += x++ * x++ * x++;
x += y;
x would now be 66, instead of 63 because the x in the second line is now 6, rather than its original 3.
Because the increment Operation ++ is added after the variable x. That's a post increment operation. That means, x is incremented after the operation is handled.
In your example the expression would be:
x += 3 * 4 * 5
First the expression is added by 3 (x+=....)
then the first x++ results in 3
the second x++ results in 4 (because it was incremented before)
and the third x++ results in 5.
If you want your variable incremented before the operation is executed, you have to write ++x (pre increment operation)
Because a postincrement modifies the variable after the value is taken and += evaluates its left hand side before evaluating its right hand side,
x += x++ * x++ * x++;
becomes
tmp0 = x
tmp1 = x
++x
tmp2 = tmp1 * x
++x
tmp3 = tmp2 * x
++x
x = tmp0 + x
unary operators evaluated left to right, so the first x++ gets the value x, the second is (x+1), etc. And the += evaluates according to the value of x at the start, hence the addition of x
Can you please help me understand what the following code means:
x += 0.1;
The "common knowledge" of programming is that x += y is an equivalent shorthand notation of x = x + y. As long as x and y are of the same type (for example, both are ints), you may consider the two statements equivalent.
However, in Java, x += y is not identical to x = x + y in general.
If x and y are of different types, the behavior of the two statements differs due to the rules of the language. For example, let's have x == 0 (int) and y == 1.1 (double):
int x = 0;
x += 1.1; // just fine; hidden cast, x == 1 after assignment
x = x + 1.1; // won't compile! 'cannot convert from double to int'
+= performs an implicit cast, whereas for + you need to explicitly cast the second operand, otherwise you'd get a compiler error.
Quote from Joshua Bloch's Java Puzzlers:
(...) compound assignment expressions automatically cast the result of
the computation they perform to the type of the variable on their
left-hand side. If the type of the result is identical to the type of
the variable, the cast has no effect. If, however, the type of the
result is wider than that of the variable, the compound
assignment operator performs a silent narrowing primitive
conversion [JLS 5.1.3].
x += y is x = x + y
x -= y is x = x - y
x *= y is x = x * y
x /= y is x = x / y
x %= y is x = x % y
x ^= y is x = x ^ y
x &= y is x = x & y
x |= y is x = x | y
and so on ...
It's one of the assignment operators. It takes the value of x, adds 0.1 to it, and then stores the result of (x + 0.1) back into x.
So:
double x = 1.3;
x += 0.1; // sets 'x' to 1.4
It's functionally identical to, but shorter than:
double x = 1.3;
x = x + 0.1;
NOTE: When doing floating-point math, things don't always work the way you think they will.
devtop += Math.pow(x[i] - mean, 2); will add the result of the operation Math.pow(x[i] - mean, 2) to the devtop variable.
A more simple example:
int devtop = 2;
devtop += 3; // devtop now equals 5
In java the default type of numbers like 2 or -2(without a fractional component) is int and unlike c# that's not an object and we can't do sth like 2.tostring as in c# and the default type of numbers like 2.5(with a fractional component) is double;
So if you write:
short s = 2;
s = s + 4;
you will get a compilation error that int cannot be cast into short also if you do sth like below:
float f = 4.6;
f = f + 4.3;
you will get two compilation errors for setting double '4.6' to a float variable at both lines and the error of first line is logical because float and double use different system of storing numbers and using one instead of another can cause data loss;
two examples mentioned can be changed like this:
s += 4
f += 4.3
which both have an implicit cast behind code and have no compile errors;
Another point worthy of consideration is numbers in the range of 'byte' data type are cached in java and thus numbers -128 to 127 are of type byte in java and so this code doesn't have any compile errors:
byte b = 127
but this one has an error indeed:
byte b = 128
because 128 is an int in java;
about long numbers we are recommended to use an L after the number for the matter of integer overflow like this:
long l = 2134324235234235L
in java we don't have operator overloading like c++ but += is overloaded only for String and not for the let's say StringBuilder or StringBuffer and we can use it instead of String 'concat' method but as we know String is immutable and that will make another object and will not change the same object as before :
String str = "Hello";
str += "World";
It's fine;
You can take a look at the bytecode whenever you want to understand how java operators work. Here if you compile:
int x = 0;
x += 0.1;
the bytecode will be accessible with jdk command javap -c [*.class]:(you can refer to Java bytecode instruction listings for more explanation about bytecode)
0: iconst_0 // load the int value 0 onto the stack
1: istore_1 // store int value into variable 1 (x)
2: iload_1 // load an int value from local variable 1 (x)
3: i2d // convert an int into a double (cast x to double)
4: ldc2_w #2 // double 0.1d -> push a constant value (0.1) from a constant pool onto the stack
7: dadd // add two doubles (pops two doubles from stack, adds them, and pushes the answer onto stack)
8: d2i // convert a double to an int (pops a value from stack, casts it to int and pushes it onto stack)
9: istore_1 // store int value into variable 1 (x)
Now it is clear that java compiler promotes x to double and then adds it with 0.1.
Finally it casts the answer to integer .
There is one interesting fact I found out that when you write:
byte b = 10;
b += 0.1;
compiler casts b to double, adds it with 0.1, casts the result which is double to integer, and finally casts it to byte and that is because there is no instruction to cast double to byte directly.
You can check the bytecode if you doubt :)
devtop += Math.pow(x[i] - mean, 2); adds Math.pow(x[i] - mean, 2) to devtop.
It increases the value of the variable by the the value after +=.
For example:
float x = 0;
x += 0.1;
//x is now 0.1
x += 0.1;
//x is now 0.2
It's just a shorter version of:
x = x+0.1;