title: How bad is declaring arrays inside a for loop in Java?
body: <p>I come from a C background, so I admit that I'm still struggling with letting go of memory management when writing in Java. Here's one issue that's come up a few times that I would love to get some elaboration on. Here are two ways to write the same routine, the only difference being when <code>double[] array</code> is declared:</p>
  
  <p><strong>Code Sample 1</strong>:</p>
  
  <pre><code>double[] array;
  for (int i=0; i&lt;n; ++i) {
      array = calculateSomethingAndReturnAnArray(i);
      if (someFunctionOnArrays(array)) {
          // DO ONE THING
      } else {
          // DO SOME OTHER THING
      }
  }
  </code></pre>
  
  <p><strong>Code Sample 2</strong>:</p>
  
  <pre><code>for (int i=0; i&lt;n; ++i) {
      double[] array = calculateSomethingAndReturnAnArray(i);
      if (someFunctionOnArrays(array)) {
          // DO ONE THING
      } else {
          // DO SOME OTHER THING
      }
  }
  </code></pre>
  
  <p>Here, <code>private double[] calculateSomethingAndReturnAnArray(int i)</code> always returns an array of the same length. I have a strong aversion to <strong>Code Sample 2</strong> because it creates a new array for each iteration when it could just overwrite the existing array. However, I think this might be one of those times when I should just sit back and let Java handle the situation for me. </p>
  
  <p>What are the reasons to prefer one of the ways over the other or are they truly identical in Java?</p>