Bug 364413

Summary: "Local variable never read" when foreach loop is used to clear an array
Product: [Eclipse Project] JDT Reporter: Menachem Salomon <msalomon>
Component: CoreAssignee: Ayushman Jain <amj87.iitr>
Status: VERIFIED INVALID QA Contact:
Severity: normal    
Priority: P3 CC: amj87.iitr, sebastian.zarnekow, srikanth_sankaran
Version: 3.6.2   
Target Milestone: 3.8 M4   
Hardware: PC   
OS: Windows XP   
Whiteboard:

Description Menachem Salomon CLA 2011-11-21 14:51:58 EST
Build Identifier: Version: 3.6.2 Build id: M20110210-1200

When a foreach loop is used to clear an array, a "Local variable never read" warning is shown for the loop variable. In my situation, the array was filled elsewhere and is being cleared to fill it from scratch. To be accurate, s is indeed not being read, but setting it to null should be important enough. In the following code (the alternate way to accomplish the same thing), no warning is generated:
    for (int i = 0; i < array.length; i++)
        array[i] = null;
while the foreach version:
    for (String s: array)
        s = null
does generate the warning.




Reproducible: Always

Steps to Reproduce:
1. Simple stand-alone class, containing the following code:
    String [] array = new String[10];
    for (String s: array)
        s = null;

2.
3.
Comment 1 Sebastian Zarnekow CLA 2011-11-21 14:56:35 EST
I'd say the warning is correct. s = null in the foreach version will not clear the array.

String[] array = new String[] {"a", "b"};
for (String s: array)
  s = null;
for (String s: array)
  if (s != null)
    throw new RuntimeException();
Comment 2 Menachem Salomon CLA 2011-11-21 15:09:02 EST
(In reply to comment #1)
> I'd say the warning is correct. s = null in the foreach version will not clear
> the array.
> 
> String[] array = new String[] {"a", "b"};
> for (String s: array)
>   s = null;
> for (String s: array)
>   if (s != null)
>     throw new RuntimeException();

You're right. My oops. Can you excuse a newbie to Java programming error?
BTW, I very appreciate the immediate response.
Comment 3 Sebastian Zarnekow CLA 2011-11-21 15:11:41 EST
(In reply to comment #2)
> You're right. My oops. Can you excuse a newbie to Java programming error?
> BTW, I very appreciate the immediate response.

You're welcome.
Comment 4 Ayushman Jain CLA 2011-11-22 01:11:24 EST
Thanks Sebastian!

Please note that the warning has been changed to "Local variable never used" in 3.7 and above. This will make more sense now. :)