Tutorials References Exercises Videos Menu
Free Website Get Certified Pro

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Constructors Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java Inner Classes Java Abstraction Java Interface Java Enums Java User Input Java Date Java ArrayList Java LinkedList Java HashMap Java HashSet Java Iterator Java Wrapper Classes Java Exceptions Java RegEx Java Threads Java Lambda

Java File Handling

Java Files Java Create/Write Files Java Read Files Java Delete Files

Java How To

Add Two Numbers

Java Reference

Java Keywords Java String Methods Java Math Methods

Java Examples

Java Examples Java Compiler Java Exercises Java Quiz Java Certificate


Java Arrays Loop


Loop Through an Array

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

The following example outputs all elements in the cars array:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
  System.out.println(cars[i]);
}

Try it Yourself »


Loop Through an Array with For-Each

There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

Syntax

for (type variable : arrayname) {
  ...
}

The following example outputs all elements in the cars array, using a "for-each" loop:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

Try it Yourself »

The example above can be read like this: for each String element (called i - as in index) in cars, print out the value of i.

If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.


Test Yourself With Exercises

Exercise:

Loop through the items in the cars array.

String[] cars = {"Volvo", "BMW", "Ford"};
 (String i : ) {
  System.out.println(i);
}

Start the Exercise