• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing by value

 
preeti dengri
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • 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 .
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic