title: Java - changing the value of a final variable from within a lambda
body: <p>In Java I have the following code </p>
  
  <pre><code>List&lt;Integer&gt; myList = new ArrayList&lt;&gt;();
  for (int i=0;i&lt;9;i++) {
      myList.add(i);
  }
  
  Integer sum = 0;
  
  myList.forEach(i -&gt; {
      sum = sum + i; // does not compile, sum needs to be final or effectively final
  });   
  
  for(int i : myList) {
      sum = sum + i; //runs without problems
  } 
  </code></pre>
  
  <p>My question is, why is it exactly that I cannot change the value of sum from within the lambda? It does the exact same thing as the for loop down below, or am I wrong? Interesting is also the fact that if I declare the Integer sum outside of the main method as static, it works as well. Can anyone explain me why? </p>
  
  <p>EDIT: In another similar question <a href="https://stackoverflow.com/questions/17204279/does-java-8-support-closures">Does Java 8 support closures</a>, the answer seems to be :</p>
  
  <blockquote>
    <p>it is a combination of backwards compatibility and project resourcing constraints.</p>
  </blockquote>
  
  <p>However I still cannot understand why it works if I make sum an array or if I declare it outside of main. I would also like to understand what is the difference between the myList.forEach and the for loop below, why the one works and the other one doesn't.</p>