• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Program

 
meena kumari
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I am new to java .I am finding difficulty in understanding the below program flow.
Can any one explain me how the program works.



public class example {
int i = 0;
public static void main(String args[]) {
int i = 1;
change_i(i);
System.out.println(i);
}
public static void change_i(int i) {
i = 2;
i *= 2;
}
}


Thanks,
Meena
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

When arguments are passed to a method, they are copies of the original value. And these copies are local to the method scope.

In this case, there is an int i defined in the class, another int i defined in the main method, and a third int i that's local to the change_i method. So when the value of i is changed within the change_i method, it's only that local value that changes. The int i within main is still 1, and the int i defined at the class level is still 0.

Compile and run the code below, which I've modified to output each of these different variables...
 
meena kumari
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marc
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic