Declaring a variable outside the forach loop in Java

Can someone comment me on the following question:

public class Loopy { public static void main(String[] args) { int[] myArray = {7, 6, 5, 4, 3, 2, 1}; int counterOne; for (counterOne = 0; counterOne < 5; counterOne++) { System.out.println(counterOne + " "); } System.out.println(counterOne + " "); int counterTwo = 0; for (counterTwo : myArray) { System.out.println(counterTwo + " "); } } } 

In the for loop, we declare counterOne outside the loop and use it inside the loop. This is correct if we do not use counterOne after the loop ends.

In the foreach loop, we also declare counterTwo outside the loop, and then use it only inside the loop. However, in this case, an error occurs:

"Exception in thread" main "java.lang.RuntimeException: Uncompilable source code - cannot find character symbol: class counterTwo location: class package1.Loopy"

Can you help me understand why?

The only difference between them is that counterOne initialized to zero, and then the values ​​are assigned step by step (less than 5).

In the foreach loop, counterTwo assigned one after another, each element of the array.

The program works if we do this in the second loop: for(int counterTwo : myArray) , and the first to work in both cases:

  • existing
  • for (counterOne = 0; counterOne < 5; counterOne++)
+6
source share
3 answers

From this section of the Java Language Specification for Enhanced for -loops:

The enhanced for statement has the following form:

EnhancedForStatement:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement

EnhancedForStatementNoShortIf:

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) StatementNoShortIf

Note that a declaration of type UnannType must be present in a for loop. Therefore, you should write a loop like this:

 for (int z : x) { 
+11
source

Well, making this simple, the second is "special" because it is actually "for everyone." Inside, a variable declaration is always required. Instead of explaining it poorly, here you refer to an older question about this, check this out: Why a variable declaration is required inside the foreach loop

+2
source

This is just a syntax for each loop. You cannot use a variable defined inside each loop outside the loop itself. That is how language is defined.

https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

0
source

Source: https://habr.com/ru/post/988595/


All Articles