aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes passing by value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "passing by value" Watch "passing by value" New topic
Author

passing by value

preeti dengri
Ranch Hand

Joined: Nov 30, 2000
Posts: 111
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

Joined: Aug 30, 2000
Posts: 3141
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


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
 
 
subject: passing by value