Forums Register Login

Operators

+Pie Number of slices to send: Send
Can anybody explain why the o/p of the following code is 1,4. I am not getting the logic:-

public class Main {
public static void main(String args[]){
int x =0;
for(int i=0; i < 2; i++){
x +=(x += ++x);
System.out.println(x);
}
}
}

Thanks in Advance
+Pie Number of slices to send: Send
Hi,

Originally posted by Chinmay Kant:
Can anybody explain why the o/p of the following code is 1,4. I am not getting the logic:-

public class Main {
public static void main(String args[]){
int x =0;
for(int i=0; i < 2; i++){
x +=(x += ++x);
System.out.println(x);
}
}
}

Thanks in Advance



I hope this helps:

1ST LOOP: x=0
x +=(x += ++x);
- Inside parentheses: x = x + (1+x) ===> x = 0 + 1 = 1
- Outside: x = x + parentheses ===> x = 0 + 1 = 1
- x = 1

2ND LOOP: x=1
x +=(x += ++x);
- Inside parentheses: x = x + (1+x) ===> x = 1 + 2 = 3
- Outside: x = x + parentheses ===> x = 1 + 3 = 4
- x = 4

Regards,
Alex
+Pie Number of slices to send: Send
I hope this helps:

1ST LOOP: x=0
x +=(x += ++x);
- Inside parentheses: x = x + (1+x) ===> x = 0 + 1 = 1
- Outside: x = x + parentheses ===> x = 0 + 1 = 1
- x = 1

Thanks Alex,
But one doubt
when ++x occurs it chagnges the value of x from 0 to 1
so, when this operation is done does that value does not affect further
calculation

for eg:-
Inside parentheses ++x changes the value to 1
so, x = x +(++x) ---> x = 1 + 1 ---> x= 2
so, wo should be used further.
+Pie Number of slices to send: Send
Ya Alex that's my doubt tooo........

when x++ happens does it change change value to 1....
+Pie Number of slices to send: Send
x +=(x += ++x);

As ++x is part of the expression, the value of x will not be modified. When the controller comes to ++x, it evaluates to increment the "VALUE" of x and replaces that value as follows,

x += (x += 1) //if x=0

Hope you got it.
+Pie Number of slices to send: Send
Thanks SrinivasaRao Madugula.........if is that the case....thanks for your answer......
+Pie Number of slices to send: Send
yeah if we consider that x still retains its previous value even after ++x the answer follows.....but the problem is why is the old value of x still retained in the expression.....anybody please elaborate...
He's my best friend. Not yours. Mine. You can have this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 826 times.
Similar Threads
Operators
Can anyone explain this code from ...Java 2 Part-1 the programmers exam - page 49
Head First Java - Can't understand the output
Array index
Local variable scope
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 00:04:19.