Tuesday 19 April 2011

Java object reference is passed by value

Today I spent a whole afternoon debugging a piece of Java code. The code is something like this:

public void captureNow(BufferedImage image) {
  try{  
    image = ImageIO.read(new File(getRecordeDir() + files[index++])); // only changes the local variable image.
  } catch (IOException ioe) {
    System.err.println(e.getMessage());
  }
}

BufferedImage bi = new BufferedImage(width, height, type);
captureNow(bi); // bi does not change.

After calling captureNow(bi), bi didn't get the image that supposed to be read. The problem here is I got confused with C++. Even though Java is pass by reference, it does not mean the same thing as in C++. Here in Java, the local variable image got the address of bi. In side the method, image is assigned another address, but this does not affect bi. In C++, a reference is automatically dereferenced to point to the actual object. Hence, an assignment will affect the actual object passed.

Edit:
As a reader pointed out, here is a good explanation about Java's pass by value.

3 comments :

  1. Java IS PASS-BY-VALUE... See http://javadude.com/articles/passbyvalue.htm

    ReplyDelete
  2. Java is always pass by value - even what looks like pass by reference is actually pass by value. This article is a good reference on the topic:

    http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-reference-or-by-value/

    ReplyDelete
    Replies
    1. Thanks. I think that's what I'm trying to explain in the body but the title conveys the wrong idea. Thank you for pointing this out.

      Delete