Why is there exception while using enhanced for loop for traversing the array in the following code? | Core Java Forum
S
Shinia Posted on 05/12/2021

package com.programming.java;
//size is used with collections and length is used with arrays
public class ArrayExample {
public static void main(String[] args) {
//declared and instantiated(length)
//index based/bitwise structure
int[] intArr=new int[10];

//initialization
intArr[0]=12;
intArr[4]=45;
intArr[8]=3;
intArr[5]=23;
intArr[5]=55;


//declared,instantiated,initialized-array structured
int[] intArr2= {3,7,9,9,8,7,6,5,8};
//traversal
//0...length-1
for(int i=0;i<intArr.length;i++)
{
System.out.println("Array elements of intArr are "+intArr[i]);
}
System.out.println();
for(int i=0; i< intArr2.length;i++) {
System.out.println("Second Array elements of intArr2 are "+intArr2[i]);
}
System.out.println();
for(int i:intArr)
{
System.out.println("Second Array elements of intArr2 using enhanced for loop are "+intArr2[i]); 

}
}
}


Y
Yogesh Chawla Replied on 06/12/2021

There was a problem with the name of the array which was being used. Now run this and see the output:

package com.programming.module7;

public class ArrayExample {
	public static void main(String[] args) {
		// declared and instantiated(length) - index based/bitwise structure
		int[] intArr = new int[10];

		// initialization
		intArr[0] = 12;
		intArr[4] = 45;
		intArr[8] = 3;
		intArr[5] = 23;
		intArr[5] = 55;

		// declared,instantiated,initialized-array structured
		int[] intArr2 = {3, 7, 9, 9, 8, 7, 6, 5, 8};
		// traversal
		// 0...length-1
		for (int i = 0; i < intArr.length; i++) {
			System.out.println("First Array elements - intArr - using basic for loop - " + intArr[i]);
		}
		
		System.out.println();
		
		for (int i = 0; i < intArr2.length; i++) {
			System.out.println(
					"Second Array element - intArr2 - using basic for loop are " + intArr2[i]);
		}
		System.out.println();
		for (int i : intArr) {
			System.out.println(
					"First Array elements of intArr using enhanced for loop are "
							+ i);

		}
	}
}


S
Shinia Replied on 06/12/2021

yeah it worked...but now...for enhanced for loop...is this a kind of syntax to be always followed for traversing an array?...I mean just using "i" instead of intArr[i]?