Community
Participate
Working Groups
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.
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();
(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.
(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.
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. :)