newprint
newprint

Reputation: 7136

The way Java handles of arguments of type class

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 !

Upvotes: 1

Views: 176

Answers (2)

Stephen C
Stephen C

Reputation: 718866

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 stream identifiers are for different variables, and that the assignment inside the method

stream = new PrintWriter(fileName);

does NOT effect the stream variable declared just before the try. The value that is assigned to the stream variable 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 return it.)

Upvotes: 2

Brian Roach
Brian Roach

Reputation: 76908

The author is trying to explain to you that changing what a variable refers to inside a method isn't visible outside the method.

toFile will be null after the call to openFile() because the reference value is passed to the method and assigned to the local stream variable. Changing the value of stream inside the method can't be seen outside the method unless you explicitly return it.

openFile() would need to return the new PrintWriter:

public static PrintWriter openFile(String fileName) throws FileNotFoundException
{
    PrintWriter stream = new PrintWriter(fileName);
    return stream;
}

and be called as:

PrintWriter toFile = null;
try
{
    toFile = openFile("data.txt");
}

Upvotes: 2

Related Questions