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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…