-1

Possible Duplicate:
Is Java pass by reference?

when I used some java class like (Integer, File, Boolean) if I pass the instance as an argument to a function and try to change its value after I use this value outside function, the value remains unchanged.

for example:

private void run(){
        File tmpFile;
        setFile(tmpFile);
        System.out.println(tmpFile.getAbsolutePath());  //error tmpFile is null
    }

private void setFile(File xFile){
    xFile = jFileChooser.getSelectedFile();  // this returned object file
}
Community
  • 1
  • 1
rChavz
  • 235
  • 3
  • 16

2 Answers2

3

The short answer is that Java uses call-by-value, not call-by-reference.

In your setFile method, your assignment to xFile only changes the local variable. It does not change the variable tmpFile in the run() method.

You should write the code so that setFile returns a value; e.g.

    private void run(){
        File tmpFile = getFile();
        System.out.println(tmpFile.getAbsolutePath());
    }

    private File getFile() {
        return jFileChooser.getSelectedFile();
    }

(Note: I changed the method name, because a method called setXXX that doesn't actually set anything is gratuitously misleading.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Java always passes by value. You shouldn't expect any other behaviour.

A method can only change an object when you pass a reference (The reference is still passed by value)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130