• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Program

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Marc
reply
    Bookmark Topic Watch Topic
  • New Topic