Wednesday, 15 January 2014

java - Why using void method that open a file would not open it? -



java - Why using void method that open a file would not open it? -

i define method:

public static void openfile(string filename, printwriter stream) throws filenotfoundexception { stream = new printwriter (filename); }

i phone call method:

printwriter tofile = null; seek { openfile ("data.txt", tofile); }

why after openfile executed, value of tofile still null?

when pass tofile, you're passing reference printwriter. reference gets copied: tofile within method reference same object, it's different reference.

modifying tofile within method changes copy, doesn't alter original. re-create gets thrown away when method terminates.

this intentional, , it's there protect you. when pass argument method, should able rely on argument not changing. if execute

dosomethingtoelement(i);

where i index something, don't want possibility value of i changed within method.

it helps compiler optimising things.

in c, pass pointer reference, changed within method, or pass reference if didn't want possibility change. in java, passed value.

note concepts need careful thinking through: tofile reference, you're passing reference by value.

java io

No comments:

Post a Comment