| Author |
why the output is like that?
|
Ng fenfen
Greenhorn
Joined: Sep 10, 2008
Posts: 4
|
|
public class Test{ public static void main (String[] args){ int i=0; while (i<=4){ xMethod(i); i++; } System.out.println("i is "+i); } public static void xMethod(int i){ do{ if(i%3!=0) System.out.print(i+" "); i--; } while(i>=1); System.out.println(); } } out is: 1 21 21 421 i is 5
|
 |
Vijitha Kumara
Bartender
Joined: Mar 24, 2008
Posts: 3670
|
|
Output is fine (as it should be) . I think you are thinking about the local variable i with instance variable i? In xMethod(int i), you are passing the value of the instance variable i to it but when you do i-- in the method it change the value of the local variable not the value of the instance variable. Because a copy of the value is passed to the method as the argument. Hope this helps.
|
SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
|
 |
Gamini Sirisena
Ranch Hand
Joined: Aug 05, 2008
Posts: 347
|
|
What do you expect it to be? What you might be missing here is that the int passed to xMethod is a "copy" of the int in the main method. Doing an i-- in xMethod will not affect the i in the main method. If this does not clear your confusion say what you expect the result to be and why you think so..
|
 |
rakesh sugirtharaj
Ranch Hand
Joined: Dec 16, 2007
Posts: 151
|
|
Well, seriously i am confused.how is 'i' an instance variable?  [ October 27, 2008: Message edited by: rakesh sugirtharaj ]
|
Cheers!
RSR
|
 |
Vijitha Kumara
Bartender
Joined: Mar 24, 2008
Posts: 3670
|
|
Sorry about it. Yes it's in the main method didn't noticed that (doesn't make any different though ) My expalnation is still valid.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
|
It is difficult to read your code; we have code tags which make it easier by preserving identation.
|
 |
 |
|
|
subject: why the output is like that?
|
|
|