- First to me Iterating
and Looping
are 2 different things.
Eg: Increment a variable till 5 is Looping.
int count = 0;
for (int i=0 ; i<5 ; i++){
count = count + 1;
}
Eg: Iterate over the Array to print out its values, is about Iteration
int[] arr = {5,10,15,20,25};
for (int i=0 ; i<arr.length ; i++){
System.out.println(arr[i]);
}
Now about all the Loops:
- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...
For Loop
:
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("The sum is " + sum);
The Difference between While and Do-While is as Follows :
- While
is a Entry Control Loop
, Condition is checked in the Beginning before entering the loop.
- Do-While
is a Exit Control Loop
, Atleast once the block is always executed then the Condition is checked.
While Loop
:
int sum = 0;
int i = 0; // i is 0 Here
while (i<100) {
sum += i;
i++;
}
System.out.println("The sum is " + sum);
do-While
:
int sum = 0;
int i = 0; // i is 0 Here
do{
sum += i;
i++
}while(i < 100; );
System.out.println("The sum is " + sum);
From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.
ArrayList<String> arr = new ArrayList<String>();
arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");
for (String str : arr){ // str represents the value in each index of arr
System.out.println(str);
}