Page 350 - CITS - Computer Software Application -TT
P. 350

COMPUTER SOFTWARE APPLICATION - CITS




           a[3]=40;
           a[4]=50;
           //traversing array
           for(int i=0;i<a.length;i++)//length is the property of array
           System.out.println(a[i]);
           }}
           Output
           10
           20
           70
           40
           50
           We can declare, instantiate and initialize the java array together by:

           int a[]={33,3,4,5};//declaration, instantiation and initialization
           Java Program to illustrate the use of declaration, instantiation
           and initialization of Java array in a single line
           class Testarray1{
           public static void main(String args[]){
           int a[]={33,3,4,5};//declaration, instantiation and initialization
           //printing array
           for(int i=0;i<a.length;i++)//length is the property of array
           System.out.println(a[i]);
           }}
           Output
           33
           3
           4
           5
           For-each Loop for Java Array
           We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by
           one. It holds an array element in a variable, then executes the body of the loop.
           The syntax of the for-each loop is given below:


           for(data_type variable:array){
           //body of the loop
           }
           Java Program to print the array elements using for-each loop
           class Testarray1{
           public static void main(String args[]){
           int arr[]={33,3,4,5};
           //printing array using for-each loop
           for(int i:arr)
           System.out.println(i);
           }}





                                                           337
                               CITS : IT&ITES - Computer Software Application - Lesson 85 - 93
   345   346   347   348   349   350   351   352   353   354   355