Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-7139681

Enhanced for loop: local variable scope inconsistent with JLS

    XMLWordPrintable

Details

    • b96
    • x86
    • windows_7
    • Verified

    Description

      FULL PRODUCT VERSION :
      javac 1.6.0_26

      ADDITIONAL OS VERSION INFORMATION :
      Windows 7 Ultimate SP1 64-bit

      A DESCRIPTION OF THE PROBLEM :
      According to the Java Language Specification, section 14.14.2, the scope of the local variable of an enhanced for loop is the enclosed statement. However, the compiler treats the for loop expression as within the scope of the local variable.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Write an enhanced for loop with a local variable name that masks an Iterable or array field and use the masked field as the loop expression. The JLS suggests that this should compile because the expression is not within scope of the local variable of the loop.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The expression should be evaluated as if it were outside the scope of the local variable of the enhanced for loop.
      ACTUAL -
      The compiler evaluates the loop expression within the scope of the local loop variable.

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
        Bug.java:8: int cannot be dereferenced
                      for (int index : index.values) {
                                            ^
      1 error


      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      public class Bug {
          private static class Foo {
              int[] values;
          }
          Foo index;

          public void method() {
              for (int index : index.values) {
                  System.out.println(index);
              }
          }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      The masked field can be qualified with "this.".

      Attachments

        Activity

          People

            mcimadamore Maurizio Cimadamore
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: