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);   
        }
    }
}
1

5 Answers 5

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);   
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.