Traversing an array

Using Enhanced For-loop

This is a specialized for loop introduced in Java SE 6 to loop through an array or collection.
It has two parts for(declaration : expression)

declaration newly declared variable of type compatible with the array element.
expression this should be an array or collection variable name or a method call that returns an array.

Syntax:

for(type variable : arrayReferenceName)
{
//Use variable
}
where, type of the variable should be the type of the array.

package com.ibytecode.arrays;
public class ArrayBasics {
	public static void main(String[] args) {
		double[] studentAvgs; //declaring an array reference
		studentAvgs = new double[5]; //creating an array object
		for(double d : studentAvgs)
			System.out.println(d);
	}
}

0.0
0.0
0.0
0.0
0.0

Legal enhanced-for loop declarations:

LivingBeing[] lives = {new Animal(), new Person(), new Plant()};
for(LivingBeing life : lives)

int[] numbers = new int[4];
for(int number : numbers)

double[][] studentAvgs = {{80.0,90.0}, {75.5, 65.5, 85.5}, {98.0}};
for(double[] avgs : studentAvgs)
{
	for(double d : avgs)
	{
	}
}

Using length variable

You can use any loop (for, while, do-while) to iterate through an array starting from first element till array’s length which you will get by using arrayName.length

package com.ibytecode.arrays;
class Person
{
	String name;
	public Person(String name) {
		this.name = name;
	}
}

public class TraversingArray {
	public static void main(String[] args) {
		Person p1 = new Person("Kumar");
		Person p2 = new Person("Dev");
		Person[] persons = {p1, p2, new Person("John"), new Person("Sri")};
		
		for(int i = 0; i < persons.length; i++)
		{
			Person p = persons[i];
			System.out.println("Person:" + i + " " + p.name);
		}
	}
}

Person:0 Kumar
Person:1 Dev
Person:2 John
Person:3 Sri

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.