For loop what does this mean?

i'm learning Java at the moment and am learning how to parse HTML.

i understand how for loops work

For example:

for(int i = 0; i < 20; i++){
}

means that i is 0, if i is less than 20 then increase by 1.

But what does this mean????

for(Element newsHeadline: newsHeadlines){
                    System.out.println(newsHeadline.attr("href"));
                }

i have tried googleing this but can't find answer

Thanks

Upvotes: 0

Views: 128

Answers (6)

Raja Danish
Raja Danish

Reputation: 235

I think it will help you.

Example:

public class Test {

   public static void main(String args[]){
      int [] numbers = {10, 20, 30, 40, 50};

      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names ={"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}
This would produce the following result:

10,20,30,40,50,
James,Larry,Tom,Lacy,

Upvotes: 0

user2575725
user2575725

Reputation:

It is for-each loop. It is shorthand for writing for loop eliminating the use of index.

String[] names = {"Alex", "Adam"};

for(int i = 0; i < names.length; i ++) {
    System.out.println(names[i]);
}

for(String name: names) {
    System.out.println(name);
}

Upvotes: 1

Beri
Beri

Reputation: 11610

For loop is a short form of original for loop, but without index of given element.

As an example:

for(Element newsHeadline: newsHeadlines){
   System.out.println(newsHeadline.attr("href"));
}

is same as:

Iterator<Element> it  = newsHeadlines.iterator();
while(it.hasNext()){
   Element newsHeadline = it.next();
   System.out.println(newsHeadline.attr("href"));
}

As you can see it is shorter and more readable. In short it means: for every element in collection do something. You can iterate over any iterable collection or array.

Upvotes: 1

Antony D&#39;Andrea
Antony D&#39;Andrea

Reputation: 1004

This is a foreach loop.

newsHeadlines is an array of objects of type Element.

for(Element newsHeadline: newsHeadlines)

Should be read as

For each newsHeadline in newsHeadlines do

It will end after it reaches the last object of newsHeadlines and finishes the code in the block.

Hopefully now that you know it is a foreach loop, it will help you refine your Google search.

Upvotes: 2

baryo
baryo

Reputation: 1461

This is an iterating loop: each iteration puts the next element of the collection newsHeadlines inside newsHeadline. Checkout this thread: How does the Java 'for each' loop work?

Upvotes: 0

euclid135
euclid135

Reputation: 1272

It's a for-each loop. It uses iterator to iterate over collection

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

Upvotes: 1

Related Questions