Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Good to know "Enhanced for loop" !!!

First I want to show you the program of enhanced for loop,

____________________________________________________

public class ForLoop {

public static void main(String[]args){

int numbers[] = {55,120,199,500,708,854,918,999,1000,1012,5000};

for(int x : numbers){

if(x>50 && x<=1000){

System.out.println("Your numbers list is "+x);
}
}
}
}
_________________________________________________

Output:


Your numbers in Array List is 55
Your numbers in Array list is 120
Your numbers in array list is 199
Your numbers in array list is 500
Your numbers in array list is 708
Your numbers in array list is 854
Your numbers in array list is 918
Your numbers in array list is 999
Your numbers in array list is 1000
__________________________________________________


Now in above program what we did new is write for loop in new way that is put " : " between it. Why we use enhanced loop. It's easy to use when we deal with arrays. Yes,  arrays. If you write a code in simple manner than how could you write is? Like as I write this.................

 _________________________________________________

public class ForLoop {

public static void main(String[]args){


int numbers[] = {55,120,199,500,708,854,918,999,1000,1012,5000};

 for(int x=0; x<=11;x++){
         
         if (numbers[x]>50 && numbers[x]<=1000){
         
         System.out.println("Your numbers in array list is "+numbers[x]);
         }
          }
}
}
________________________________________________


Output:

Your numbers in array list is 55
Your numbers in array list is 120
Your numbers in array list is 199
Your numbers in array list is 500
Your numbers in array list is 708
Your numbers in array list is 854
Your numbers in array list is 918
Your numbers in array list is 999
Your numbers in array list is 1000
__________________________________________________


Now you can see the difference in both program and you can find that it's easy to define in enhance for loop rather than simple for loop. It also give you accurate output. 

Now you also might be surprise that why we get output till 1000 and the numbers written in arrays are till 5000. That's all because of  "&&" , "and" condition mean both condition must be fulfill and only after that it give you the output. 

Now just change "&&" to "||", now you can see the out put till "5000" that's because "or" condition, according that any one condition must be fulfill so that we can go ahead.  


Thanks for spend your valuable time.....................




This post first appeared on LET's START CORE JAVA !, please read the originial post: here

Share the post

Good to know "Enhanced for loop" !!!

×

Subscribe to Let's Start Core Java !

Get updates delivered right to your inbox!

Thank you for your subscription

×