[java] Java for loop syntax: "for (T obj : objects)"

I came across some Java syntax that I haven't seen before. I was wondering if someone could tell me what's going on here.

for (ObjectType objectName : collectionName.getObjects())

This question is related to java syntax for-loop foreach

The answer is


It's called a for-each or enhanced for statement. See the JLS §14.14.2.

It's syntactic sugar provided by the compiler for iterating over Iterables and arrays. The following are equivalent ways to iterate over a list:

List<Foo> foos = ...;
for (Foo foo : foos)
{
    foo.bar();
}

// equivalent to:
List<Foo> foos = ...;
for (Iterator<Foo> iter = foos.iterator(); iter.hasNext();)
{
    Foo foo = iter.next();
    foo.bar();
}

and these are two equivalent ways to iterate over an array:

int[] nums = ...;
for (int num : nums)
{
    System.out.println(num);
}

// equivalent to:
int[] nums = ...;
for (int i=0; i<nums.length; i++)
{
    int num = nums[i];
    System.out.println(num);
}

Further reading


The variable objectSummary holds the current object of type S3ObjectSummary returned from the objectListing.getObjectSummaries() and iterate over the collection.

Here is an example of this enhanced for loop from Java Tutorials

class EnhancedForDemo {
 public static void main(String[] args){
      int[] numbers = {1,2,3,4,5,6,7,8,9,10};
      for (int item : numbers) {
        System.out.println("Count is: " + item);
      }
 }
}

In this example, the variable item holds the current value from the numbers array.

Output is as follows:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Hope this helps !


yes... This is for each loop in java.

Generally this loop is become useful when you are retrieving data or object from the database.

Syntex :

for(Object obj : Collection obj)
{
     //Code enter code here
}

Example :

for(User user : userList)
{
     System.out.println("USer NAme :" + user.name);
   // etc etc
}

This is for each loop.

it will incremental by automatically. one by one from collection to USer object data has been filled. and working.


That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries().


Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.

for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }


for each S3ObjecrSummary in objectListing.getObjectSummaries()

it's looping through each item in the collection


public class ForEachLoopExample {

    public static void main(String[] args) {

        System.out.println("For Each Loop Example: ");

        int[] intArray = { 1,2,3,4,5 };

        //Here iteration starts from index 0 to last index
        for(int i : intArray)
            System.out.println(i);
    }

}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?