jII
jII

Reputation: 1155

How does Java allocate memory differently for an object declared in a constructor and an object named by a variable?

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

Answers (3)

Sultan
Sultan

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

Aaron Digulla
Aaron Digulla

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

Akhi
Akhi

Reputation: 2242

No Difference.Both Are the same.

Upvotes: 2

Related Questions