class ArrayDemo
{
public static void main(String[] args)
{
// declares an array of Strings and allocates memory for 10 Strings
String[] strArray = new String[10];
// initialize first element
strArray[0] = "Apple";
// initialize second element
strArray[1] = "Ball";
// and so forth
strArray[2] = "Car";
strArray[3] = "Dog";
strArray[4] = "Eagle";
strArray[5] = "Fox";
strArray[6] = "Girl";
strArray[7] = "Horse";
strArray[8] = "Ink";
strArray[9] = "Jack";
System.out.println("Element at index 0: " + strArray[0]);
System.out.println("Element at index 1: " + strArray[1]);
System.out.println("Element at index 2: " + strArray[2]);
System.out.println("Element at index 3: " + strArray[3]);
System.out.println("Element at index 4: " + strArray[4]);
System.out.println("Element at index 5: " + strArray[5]);
System.out.println("Element at index 6: " + strArray[6]);
System.out.println("Element at index 7: " + strArray[7]);
System.out.println("Element at index 8: " + strArray[8]);
System.out.println("Element at index 9: " + strArray[9]);
}
}
Output Element at index 0: Apple
Element at index 1: Ball
Element at index 2: Car
Element at index 3: Dog
Element at index 4: Eagle
Element at index 5: Fox
Element at index 6: Girl
Element at index 7: Horse
Element at index 8: Ink
Element at index 9: Jack
ArrayLoopDemo.java class ArrayLoopDemo
{
public static void main(String[] args)
{
// declares an array of Strings and allocates memory for 10 Strings
String[] strArray = new String[10];
// initialize first element
strArray[0] = "Apple";
// initialize second element
strArray[1] = "Ball";
// and so forth
strArray[2] = "Car";
strArray[3] = "Dog";
strArray[4] = "Eagle";
strArray[5] = "Fox";
strArray[6] = "Girl";
strArray[7] = "Horse";
strArray[8] = "Ink";
strArray[9] = "Jack";
System.out.println("Using For-each loop getting each element from the String Array\n");
/*
* Using For-each loop get all elements from strArray
*/
int i=0;
for (String value : strArray)
{
System.out.println("Element at index " +i+" : "+ value);
++i;
}
}
}
Output Using For-each loop getting each element from the String Array
Element at index 0 : Apple
Element at index 1 : Ball
Element at index 2 : Car
Element at index 3 : Dog
Element at index 4 : Eagle
Element at index 5 : Fox
Element at index 6 : Girl
Element at index 7 : Horse
Element at index 8 : Ink
Element at index 9 : Jack