Question

Let we have a Student class. Form the following code snippet (Java) we know -

Student aStudent = new Student();
  1. A 'Student' type reference variable is created
  2. An object of 'Student' is created with the 'new Student()'
  3. The object is assigned with the reference variable 'aStudent'

So far I know, each time we write 'new Student()' a new object is created and the newly created object is allocated a memory space. But sometimes we write something like this in a for loop -

for ( int i=0; i<10000; i++) {
 Student student  = new Student();
 ...
 ...
 ...
}

In this situation -

  1. does JVM create new object of Student 10000 times? Or any optimization is occurred behind the scene to save memory.
  2. If any optimization occurred then how it is done? And how can I know the number of actually created object in the for loop.

Thanks in advance.

Was it helpful?

Solution

1.does JVM create new object of Student 10000 times? Or any optimization is occurred behind the scene to save memory.

Yes. 10,000 Student objects will be created. And at the end all 10000 of them CANNOT be accessed because all the objects and references will go out of scope (yes 10000 references will be created. 1 for each object). All the objects and references (named student) will go out of scope and will be ready for GC.

2.If any optimization occurred then how it is done? And how can I know the number of actually created object in the for loop

I am not aware of any optimizations being done by the compiler in this scenario. But what I know is if you use a static code analysis tool like codePro, it will mark this code as a warning. i.e, you should not create objects in a loop.

OTHER TIPS

Sorry if this answer isn't accurate since I'm relatively new to Java.

From my understanding yes 10000 objects will be created but all but 1 of them will be eligible for Garbage collection since there is nothing pointing to the other objects.

The Garbage collector is the only optimization that goes on behind the scenes, however it cannot be called directly but you can suggest for an object to be garbage collected by simply setting it to null ie: student = null;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top