Foreach loop in Java

Hello friends how are you, today in this blog i will teach you what is foreach loop, syntax of foreach loop , how foreach loop works and many programs using foreach loop in a very simple way. 

Let's start 

Foreach loop in Java

 

  • It is a special type of loop which is used mostly with array.
  • It stores each element of array in a variable and executes the body of loop.
  • It starts with for keyword like a normal for loop.
  • If you want to access all the elements of array in a very simple then this loop is very useful.

Here in the below program we are going to print all the elements of an array using foreach loop. As we know that we can access the elements of an array using index number which starts from zero. But here the important point is that we can access all the elements of array without index using foreach loop.


class Easy
{
 public static void main(String[] args) 
 {
  //array declaration
  int ar[]={10,50,60,80,90};
  for (int element:ar) 
   System.out.print(element+" ");       
 }
}
/*
### Output ###
10 50 60 80 90
*/

Here  i am going to print all the elements of same array using for loop so that you could understand this in a very simple way.

class Easy
{
 public static void main(String[] args) 
 {
  //array declaration
  int ar[]={10,50,60,80,90};
  for (int i = 0; i <ar.length; i++) 
   System.out.print(ar[i]+" ");       
 }
}
/*
### Output ###
10 50 60 80 90
*/


Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. Thanks.😊

Post a Comment

0 Comments