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
In simple cases like this, there is most likely no difference and compiler produces exactly the same code (assuming you do not set the initial value when declaring the variable).
In more complex cases and longer functions, declaring local variable inside the loop or other block is likely to be more efficient. This shortens the lifetime of the variable thus making it easier for compiler to optimize the code. When a variable does not exist outside the block, the register used to store the variable can be used for other purposes.
This, of course, depends on the compiler implementation. I don't know about Java, but at least some C compiler manufacturers have given this recommendation in their documentation.
As for readability, my opinion is that in short functions it is better to declare all variables at the beginning where they can be easily found. In very long functions (which should be avoided anyway), it may be better to declare the variable inside a block (which just happens to be more efficient, too).