title: Private, Static, and scope of variables in Java
body: <p>In my Java class, we just learned about scope. And by learned I mean it was briefly mentioned once and never spoken of again. Some questions were posted, and I'm having trouble understanding the difference between two pieces of code. The first one:</p>
  
  <pre><code>public class Shadow3 {
      private static int i = 99;
      public static void main(String[] args) {
          for (int i = 0; i &lt; 10; i++) {
              System.out.println(i);
          }
          System.out.println(i);
      }
  }
  </code></pre>
  
  <p>And the second one:</p>
  
  <pre><code>public class Shadow4 {
      private int i;
      public void doSomething(int n) {
          for (int i = 0; i &lt; n; i++) {
              System.out.println(i);
          }
      }
      public static void main(String[] args) {
          new Shadow4().doSomething(9);
      }
  }
  </code></pre>
  
  <p>I understand that the error with the first one is not that the variable is declared twice, but I don't understand why the scope of the variable declared in the Shadow class doesn't reach the main method to cause a duplication error. I also understand why in the first piece of code, the variable i cannot be declared as private static when it is then used in the for loop, because the values of i in the for loop are temporary, but I don't understand how then the variable i in the second piece of code is valid, because it is still private.</p>