Reputation: 1155
Using Java IO streams, it is quite often we use objects solely as constructors for other objects. I am interested in the memory implications of this prospect. For example, how does memory allocation differ in these two statements that do the same thing?
FileInputStream inputFile = new FileInputStream("filepath");
Scanner inStream = new Scanner(inputFile);
and
Scanner inStream = new Scanner(new FileInputStream("filepath"));
Upvotes: 2
Views: 251
Reputation: 41
In the first example, the JVM keeps a reference of the FileInputStream, while the second way the JVM creates an unreferenced object that is ready to be garbage-collected after the execution of the statement.
Upvotes: 0
Reputation: 328536
The first one will allocate a named variable in the current stack frame. On the heap, there is no difference - or there shouldn't be but the VM is of course free to optimize the code in some way as long as the rules are obeyed.
Upvotes: 4