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
While your example is a hypothetical, most likely not real world application, the simple answer is that you don't need a variable at all in this scenario. There is no reason to allocate the memory. Simply put it's wasted memory that becomes cannon fodder in the JVM. You've already allocated memory to store the value in a List, why duplicate it in another variable?
The scope of the variable's use will often dictate where it should be declared. For instance:
Connection conn = null;
try {
conn.open();
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
}
The other answers do a good job of exposing the other pitfalls of the example you provided. There are better ways to iterate through a list, whether it's with an actual Iterator, or a foreach loop, and generics will help eliminate the need to create a primitive duplicate.