Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why the output is like that?

 
Ng fenfen
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, seriously i am confused.how is 'i' an instance variable?
[ October 27, 2008: Message edited by: rakesh sugirtharaj ]
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is difficult to read your code; we have code tags which make it easier by preserving identation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic