0

Sometimes some guys tell, I'd better to define variables in the "for" loop, and other times some guys tell me I should define outside of "for" loop. I am very confused.

Could some guys tell me which is better when it comes to Android?

Thank you for your time.

AmyWuGo
  • 2,315
  • 4
  • 22
  • 26
  • 1
    Look at http://weblogs.java.net/blog/ddevore/archive/2006/08/declare_variabl.html and http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop – user370305 Sep 10 '12 at 08:27
  • 1
    You can take reference of this post. http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop – nisha.113a5 Sep 10 '12 at 08:37

1 Answers1

0

Defining is the part where you give a value to a variable. It shouls be done in the proper scope. If you value depends on the iteration, then, obviously, it has to be done inside the loop. If it doesn't, there is no reason to reassign the value at every turn. See :

for (A a : B) {
    c = "constant"
}

doesn't make sense.

However, declaration can be discussed. It can be placed outside as it allocates the pointer memory only once, but it can be placed inside if it has a limited scope and don't need to exist outside the loop.

njzk2
  • 38,969
  • 7
  • 69
  • 107