+ 4

Increments Operator Precedence

int x = 10, y = 10; x = x++ * ++x; y = ++y * y++; System.out.println(x + " " + y); Output: 120 121 Why?

12th Oct 2018, 8:29 PM
Roger Wang
Roger Wang - avatar
6 Antworten
+ 6
x = x++ * ++x well x++ first takes the value of x(10) and then adds 1 x=11 so now we have 10 * ++x and we added 1 to x's value x=11 now then ++x first adds 1 to the current calue of x(11) to be 12 and then it multiplies so it does 10 * 12 = 120 ++y * y++ does this add 1 to that value y(10) to be y(11) so we have 11 * y++ now and y=11 then we do y++ which first takes y's value (11) and then adds one y(12) so the function will do 11 * 11 and output 121
12th Oct 2018, 8:44 PM
Roel
Roel - avatar
+ 4
It's simple. prefix(++x) increments first, then assigns and suffix(x++) assigns or calculates first them increments. See, lessonhttps://www.sololearn.com/learn/JavaScript/1130/ If you still not get: For x, x++ increments after multiplication, and ++x increments before multiplication. so, first term would be 10 and second would be 12. Similarly for y, ++y increments before multiplication and y++ increments after multiplication. So, first term would be 11 and second also.
12th Oct 2018, 8:40 PM
Roneel
Roneel - avatar
+ 3
y = ++y * ++y will output 132
12th Oct 2018, 8:50 PM
Roneel
Roneel - avatar
+ 2
Roel is there any way to increment both numbers first? y = (++y) * (y++); // Outputs 121
12th Oct 2018, 8:48 PM
Roger Wang
Roger Wang - avatar
+ 1
if you mean something like this you want to y = 11 * 12 you could do int y = 10 y = ++y * ++y; since they first increase and then take the value of y also I'd recommend you trying a lot with increments to get to know then better
12th Oct 2018, 8:50 PM
Roel
Roel - avatar
+ 1
in the first equation our initial value of x is 10 ... during x++ it first uses value of x as 10 and then it add 1 to it, thus now x value is 11 which when used as ++x , first 1 is added to the value of x (that was 11) and then used as 12... so, x=x++*++x =10*12=120 in the second one, initial value of y is 10 which when used as ++y first gets increased by 1 and then the value is put as 11.. after that it is y++ which means that first the value stored in y(that was 11) is used and then it is increased.. so, y=++y*y++ =11*11=121 Hope it helps you... ^_^
13th Oct 2018, 6:17 PM
mn121
mn121 - avatar