Sat. Dec 21st, 2024

This loop is introduced in java 1.5 version and it designed for accessing the elements from arrays (collection). It is also called as enhanced for loop.

Syntax:

for(declaration:arrayname){

statements;

}

The declaration of a variable in for loop must as that of the type of elements available in the array. In for each loop, the statements will be executed one time for each elements available in the array and therefore called for each loop.

Program:

Class ArrayDemo{
   Public static void main(string[] args){
    int arr;
    arr= new int[5];
    System.out.println(arr[0]);
    System.out.println(arr[1]);
    System.out.println(arr[2]);
    System.out.println(arr[3]);
    System.out.println(arr[4]);

    arr[0]=11;
    arr[1]=22;
    arr[2]=33;
    arr[3]=44;
    arr[4]=55;

    for (int i=0;i<arr.length; i++){
     System.out.println(arr[i]);
   }

   for (int x: arr){
   System.out.println(x);
   }
}

}

Declaring, Creating, and assigning the array elements in a single line

Syntax

datatype arrayName[]={list of values};

Within { } we can specify any number of values separated by a comma

  1. When we decalring, creating and assigning the values in a single line, then we need not specify the size of the array.
  2. The creation of array will be done by JVM and the size of the array is also decided by JVM based on number of values specified within the { }.
  3. Once the size of the array is decided the JVM itself will assign the values to the array element.

Example:

int[] arr={10,20,30,40,50}

Program

Class ArrayDemo{
  Public static void main(string[] args){
    int[] iarr={12, 34, 45, 67,89};
     for (int x: iarr){
      System.out.println(x);
    }

   double []darr={1.1, 2.2,3.3, 4.4.,5.5,6.6}
   for (double y: darr){
   System.out.println(y);
   }

   char []carr={'a', 'b','c','d'}
   for (char z: carr){
   System.out.println(z);
  }
}
}

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *