I am looking at example in the example in Walter Savitch book “Java Introduction”
// This method does not do what we want it to do.
public static void openFile(String fileName,
PrintWriter stream) throws FileNotFoundException
{
stream = new PrintWriter(fileName);
}
PrintWriter toFile = null;
try
{
openFile("data.txt", toFile);
}
Author gives explanation, which does not make any sense, as to why toFile = null after try
Thanks !
You need to read that section of the book more deeply. (I’m sure that it actually DOES make sense … but you just haven’t understood it yet.)
It is clear that the author is actually trying to illustrate an very important aspect of Java … how parameters are passed.
Specifically, he is trying to illustrate that the two
streamidentifiers are for different variables, and that the assignment inside the methoddoes NOT effect the
streamvariable declared just before thetry. The value that is assigned to thestreamvariable inside the method gets lost.This illustrates that Java uses “pass by value” as its parameter passing mechanism. (If you need to get a value back from a method call, the simple way to do it is to
returnit.)