What is enhanced for loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What is enhanced for loop?

18th Jul 2016, 2:42 PM
WPimpong - avatar
2 Answers
+ 2
It is used to traverse an array like- for (declaration : expression){ // statement } As it is very useful to do the same thing without calling the count variable. For example public class Program { public static void main(String[] args) { int[ ] primes = {2, 3, 5, 7}; for (int t: primes) { System.out.println(t); } } }
18th Jul 2016, 5:49 PM
AnsHuman Aaditya
AnsHuman Aaditya - avatar
+ 2
This means you have to use a regular For loop for getting each object in the array so it takes time to give an index and get each object one by one. But with enhanced type it will use each object in array by itself and you don't need to define it. e.g. int[] arr={1,2,3}; for (x=0;x <arr.length;x++) { System.out.println(arr[x]); } instead int[] arr={1,2,3}; for (int t: arr) { System.out.println(t); }
19th Jul 2016, 3:01 PM
Mojtaba - avatar