This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Why is the output to i = 2 in the following scenario? I applied the logic discussed by Maha, the value should be i = 0. Can any one explain this? URL for maha's discussion: http://www.javaranch.com/ubb/Forum24/HTML/000775.html public class add { public static void main(String args[]) { int i =0, j =2; do { i = ++i; j--; }while (j>0); System.out.println("i value " + i); } }
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
0
The do while is going to execute 2 times, the first time through j=2(then 1) the second time through j=1(then 0) - and now the loop ends. The first time through the loop the i = (bump to 1 first)1; The second time through the loop the i = (bump to 2 first)2;
"JavaRanch, where the deer and the Certified play" - David O'Meara
natarajan meghanathan
Ranch Hand
Joined: Feb 01, 2001
Posts: 130
posted
0
Hi, The loop is executed twice. Since it is a do-while it is executed once atleast. So after the first execution, j=1 (>0). So it is executed again. now j=0 (not >0). So control comes out of the loop. Each time the loop is executed, u r incrementing i once. So i=2 finally when u print outside the loop.
Sun Certified Programmer for Java 2 Platform
Ananda Kashyap
Greenhorn
Joined: Jan 03, 2001
Posts: 23
posted
0
If you put i = i++; instead of i = ++i; then only the answer will be 0, that was a earlier discussion. - Ananda.
Alamu Vinai
Greenhorn
Joined: Feb 01, 2001
Posts: 19
posted
0
I think I should have explained it clearly. I know the loop is executed two times. As per Maha, "Be careful when the assigned var is the same as the var which undergone all these ++/-- operations in the statement. In this case the assigned var takes its latest value" i = 0; i = ++i; The value is assigned to i again. As per the logic of Maha, i = [1]0; and i gets the latest value, which is 0 here. The value of i should be 0. Not 2. Also, in the above program, if you substitue the line i = i++, the value of i after the loop is 0. Can any one explain me this?
natarajan meghanathan
Ranch Hand
Joined: Feb 01, 2001
Posts: 130
posted
0
Thats a beauty. I made a mistake in one of the mock tests. i=i++; ok. first i=0; then i=i++; i is assigned 0 first, then incremented (but of no use). i on the LHS has been assigned 0. This happens again for the second time. So u get i printed out to be 0.