File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "passing by value" Watch "passing by value" New topic

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();
public void amethod(int x){
the output is
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; of the code
System.out.println(p.j); 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
I agree. Here's the link:
subject: passing by value
It's not a secret anymore!