Thursday, 5 November 2020

Enhanced for loop in JAVA

 

 

Enhanced for loop in JAVA 


As of Java 5, the  enhanced  for loop was  introduced.This is mainly used for arrays.


The syntax  of enhanced  for loop  is :-


for(declaration : expression)

 {

      // Statement 

   }



Declaration : - 

  The newly  declared block variable , Which  is  of a type compatible with  the elements  of  the array  we are accessing . The variable  will be available within  the for  block  and  its  value would  be the  same as the current array  element .



Expression  :-

 This  evaluates to  the array  we  need  to loop  through. The expression  can be an array  variable  or method  call that  returns an array .



EXAMPLE :-


 public class Test 

 {

      public static void main(String  args[])

        {

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

            for(int x :numbers)

             {

                 System.out.print(x);

                 System.out.print(",");

              }

 

System.out.print("\n");

String [] names ={"Sanika","Chahat","Ritesh","Simran"};

   

   for(String name :names)

      {

          System.out.print(name);

          System .out.print(",");

        }

 

     }

 }  




OUTPUT :-


10 , 20 , 30 , 40 , 50 ,

Sanika , Chahat , Ritesh , Simran ,




 

No comments:

Post a Comment

Student Marks Calculation app using java

      import javax.swing. *; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; public class Student { private J...