Java Practices – What Happens if an InputStream is Closed When Passed as an Argument

javaprogramming practices

I have read that Java is pass-by-value, and I've been reading about it in this question at StackOverflow, but I'm still a bit confused, regarding the close() or shutdown() methods in various classes.

What I want to know is, suppose that I do this:

public Constructor(){

    if(isProceeding){
        InputStream iStream = new InputStream();
        processStuff(iStream);
    }
}


public void processStuff(InputStream stream){
    //do stuff
    stream.close();
}

Does the iStream variable actually get closed in processStuff() method or a copy of it gets closed and iStream itself is still left open?

Best Answer

Objects that are passed around to other methods can be changed by the method, and the caller will notice the change. If you let someone else use your Stream, they might close it and you'd never notice until you try to write and fail. That's why it's usually a good idea not to pass mutable objects around outside your control.

Confusion often arises because many textbooks categorically say "Java has pass-by-value semantics". That is technically true, but not very helpful for a language learner. Technically, it's not the object that gets passed around but a reference to an object, and the called method gets a copy of the reference, which of course references the same object.

But in practice, the difference between object and object reference is often not clear in people's minds. Nobody is ever interested in the value of a reference other than to check whether or not it is null. In fact, Java doesn't even have a dereferencing syntax apart from the member selector .. What people care about is the state of the underlying object. So effectively this means that mutable objects are passed by reference in the sense that the caller gets to change them, and you might be affected by that. In this sense, the textbook explanation is correct and useful for primitive types, but correct and misleading for object types.

Related Topic