Is declaring a variable inside a loop is good or declaring on the fly optimal in Java.Also is there any performance cost involved while declaring inside the loop?
eg
Besides the useful suggestions given by others, please do keep in mind one thing:
never optimize early. If you really think your code is slow and might need improvement, then use a profiler for your code to spot where the bottlenecks are, and only then do refactor them. Learn where the mistake was. Do not repeat mistake next time.
In your case I would say that, depending on the java VM version, your performance (guess what) might vary. Out of experience I'd not declare a variable within a loop; an int will certainly be optimized out by the compiler and re-use the same memory address, and the extra computational cost might be negligible.
But.
If you were declaring an object inside a loop, then things will be different. What if your object, when created, does an I/O write? A network DNS lookup? You might not know/care. So, best practice is declare it ouside.
Also, do not mix up performance with best practice. They might lead you into dangerous territory.