1

I am trying to write an imageloading function for my program, however it is doing something strange.

public void loadImage(BufferedImage img, String filepath) {
    try {
        img = ImageIO.read(new File(filepath));
    }
    catch (IOException e) {
    }
}

And I am calling it like so:

BufferedImage background = null;
loadImage(background, path);

I see in debugging that img loads properly, but background remains null the whole time and causes a NullPointerException.

When I change to a direct reference to background like background = ImageIO.read(new File(filepath)); then it works just fine.

What's even more strange is that System.out.println(img == background) prints true. What am I doing wrong?

1 Answers1

1

This is because Java passes arguments by value, not reference. As far as Java is concerned, img from loadImage has nothing to do with background. All you did was pass over the address to whatever background refers to, not the reference background itself. background basically told the parameter img, "Hey, point at whatever I'm pointing at."

When you go

img = ImageIO.read(new File(filepath));

You've just set img to refer to some new object, but background will still refer to whatever it was referring to before.

Instead, you should return the BufferedImage and set background to the return value, so something like

public BufferedImage loadImage(String filepath) {
    try {
        return ImageIO.read(new File(filepath));
    }
    catch (IOException e) {
    }
   return null;
}

background = loadImage(path);

This previous question has a little more info on the Pass-by-Value vs Pass-by-Reference issue in Java. Personally, the idea of the value of references being passed took me a while to get it through my head until I read this article.

Hope this helps.


As for your second note that img == background returns true, I'm not sure where you are checking this, but if you check it before img = ImageIO..., that will return true, because img and background both refer to null, since they are uninitialized.

==, when dealing with two Objects, will return true if and only if they both refer to the same object in memory, not if they are the same exact reference.

Community
  • 1
  • 1
Zach L
  • 16,072
  • 4
  • 38
  • 39