-------------------------------------------------------------------------------------------------------------------------
Enhanced for loop is applicable only for arrays,
Arrays can be of int or string type...
let's see the old style of writing of for loop in java.
Enhanced for loop is applicable only for arrays,
Arrays can be of int or string type...
let's see the old style of writing of for loop in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class ForLoop { public static void main(String[] args) { //old style of writing for loop int arr_int[] = {0,1,2,3,4}; //can write: int[] arr_int = {0,1,2,3,4}; for (int i=0; i< arr_int.length; i++) { System.out.println("Array element [" +i+"] is "+arr_int[i]); } String arr_str[] = {"A1","B2","C3","D4"}; //For string array for (int i=0; i< arr_str.length; i++) { System.out.println("Array element [" +i+"] is "+arr_str[i]); } } } |
Let's see the advanced for loop: Syntax: for(dataType VarName : CollectionArray)
1 2 3 4 5 6 7 8 9 10 | public class AdvForLoop { public static void main(String[] args) { //let's see the advanced for loop int k = 0; for(String s:arr_str) //short as compared to: for (int i=0; i< arr_str.length; i++) { System.out.println("Array element [" + k++ +"] is "+s); } } } |
No comments:
Post a Comment