2

Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?

public class foreachloop {
    public static void main (String [] args) {
        int [] smallprimes= new int [3]; 
        smallprimes[0]=2;
        smallprimes[1]=3;
        smallprimes[2]=5;

        // for each loop
        for (int element:smallprimes) {
            System.out.println("smallprimes="+element);   
        }
    }
}
john_science
  • 6,325
  • 6
  • 43
  • 60
Michael Bell
  • 184
  • 1
  • 2
  • 16
  • it's not a constructor. it's a valid for loop. possible duplicate of http://stackoverflow.com/questions/3912765/iterator-for-array – Prasanth Oct 01 '12 at 19:11

5 Answers5

1

It's another way to say: for each element in the array smallprimes.

It's equivalent to

for (int i=0; i< smallprimes.length; i++)
{
     int element=smallprimes[i];
     System.out.println("smallprimes="+element);   
}
Majid Laissi
  • 19,188
  • 19
  • 68
  • 105
0

This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.

See the Java Tutorial for details.

0
for(declaration : expression)

The two pieces of the for statement are:

declaration The newly declared block variable, of a type compatible with the elements of the array you are accessing. This variable will be available within the for block, and its value will be the same as the current array element. expression This must evaluate to the array you want to loop through. This could be an array variable or a method call that returns an array. The array can be any type: primitives, objects, even arrays of arrays.

Jimmy
  • 2,589
  • 21
  • 31
0

That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.

The i variable is updated at the beginning of each iteration with a value from the array.

Raffaele
  • 20,627
  • 6
  • 47
  • 86
0

Since there are not constructors in your code snippet it seems you are confused with terminology.

There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.

The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.

AlexR
  • 114,158
  • 16
  • 130
  • 208