Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: reference defined within a loop

I'm just curious.
suppose I define a reference inside a while/for loop.

does the JVM define this reference every iteration, or it's optimized to define it only once?

like image 922
socksocket Avatar asked Oct 12 '12 18:10

socksocket


People also ask

Can I declare a data type inside loop in Java?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Is it good to declare variable inside for loop in Java?

It's the result of JVM specifications... But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). It is the result of the JVM Soecification, not 'compiler optimization'.

Can you declare a variable in a while loop Java?

Yes. you can declare a variable inside any loop(includes do while loop.


2 Answers

It defines every time and scoped to only that loop iteration.

As soon as loop iteration done, it is eligible for GC.

As Louis Wasserman commented, The variable will be reinitialized every time, but the memory space will probably get reused.

like image 190
kosa Avatar answered Sep 25 '22 14:09

kosa


The reference is defined on each iteration. Once the code has been optimised to native code, it could be moved outside the loop so it doesn't have to have a performance impact. If you set this reference to a new object each time, it may create a new object on each iteration unless that object creation has been optimised away also.

like image 21
Peter Lawrey Avatar answered Sep 22 '22 14:09

Peter Lawrey