Is there a shorter way to write a for loop in Java?

user30189 picture user30189 · Feb 6, 2017 · Viewed 14.7k times · Source

the code is

 for(int i = 0; i < max; i++) {
    //do something
 }

I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max)

It could not be that much shorter, but considering how much this code is used, it would be quite helpful.

I know in python there is the range function which is much quicker to type.

Answer

Abdulgood89 picture Abdulgood89 · Feb 6, 2017

When looping through collections, you can use enhanced loops:

int[] numbers = 
 {1,2,3,4,5,6,7,8,9,10};

for (int item : numbers) {
   System.out.println(item);
}