title: Java: instantiate variables in loop: good or bad style?
body: <p>Ive got one simple question. Normally I write code like this:</p>
  
  <pre><code>String myString = "hello";
  
  for (int i=0, i&lt;10; i++)
  {
    myString = "hello again";
  }
  </code></pre>
  
  <p>Because I think the following would not be good style cause it would create too many unnecessary objects. </p>
  
  <pre><code>for (int i=0, i&lt;10; i++)
  {
    String myString = "hello again";
  }
  </code></pre>
  
  <p>Is this even correct? Or is this just the case when Ive got an explicit object like an object from a class I created? What if it was a boolean or an int? What is better coding style? Instantiate it once before the loop and use it in the loop or instantiate it every time in the loop again? And why? Because the program is faster or less storage is used or...?</p>
  
  <p>Some one told me, if it was a boolean I should instantiate it directly in the loop. He said it would not make a difference for the heap and it would be more clear that the variable belongs inside the loop. So what is correct?</p>
  
  <p>Thanks for an answer! :-)</p>
  
  <p>====</p>
  
  <p>Thanks for all your answers!</p>
  
  <p>In conclusion: it is preferable to declare an object inside the smallest scope possible. There are no performance improvements by declaring and instantiating objects outside the loop, even if in every looping the object is reinstantiated. </p>