• 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

passing by value

 
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
here is a ques from marcus green mock ex 1
public class Pass{
static int j=20;
public static void main(String argv[]){
int i=10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}
public void amethod(int x){
x=x*2;
j=j*2;
}
}
the output is
10
40
i understand why it is coz the var j is declared static and is therfore changed to a new value which is visible outside the method as well.but if we make it non static i.e
public class Pass{
int j=20;
.........rest of the code
System.out.println(p.j);
.......rest of the code
the ans is still the same.why???isn't that primitives are passed by value and whatever change takes place inside the method it is not reflected in the original .
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi preeti,
The JVM interprets <code>j = j*2;</code> as <code>this.j = this.j *2</code>. You are not passing a parameter, you are directly accessing the current object. Changing 'j' to an instance variable does not hide it from the method; both are members of the same object.
If you change the code to:

ie setup a parameter variable named 'j' it hides the instance variable 'j' and the output is '10, 20'. (The same would be true if 'j' was left as 'static')
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic