I've seen somewhere the following syntax :
int i = index;
for (; i < anArray.length();)
is it similar to a while loop ?
while(i < anArray.length()) {
// some stuff }.
Thanks
I've seen somewhere the following syntax :
int i = index;
for (; i < anArray.length();)
is it similar to a while loop ?
while(i < anArray.length()) {
// some stuff }.
Thanks
If you look at the java documentation :
for (initialization; termination;increment) {
statement(s)
}
writing for (; i < anArray.length();)
means that you don't initalize and increment anything. You'll only go out the for loop if i < anArray.length()
. So yes, it is the same but I would doubt the utility of a for loop in this case.
More information from the same doc page :
Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
// infinite loop
for ( ; ; ) {
// your code goes here
}
the for-loop is mostly used to iterate through a container (An Iterator or whatnot) So if you have a container of objects and you wish to manage something on all of them, a for-loop is a good way to go.
The while-loop however is mostly used to repeat a block of code until a condition is true:
boolean succesful = false;
while(!succesful) // runs until condition is false
{
if(connectionToInternetIsSuccesful)
succesful = true;
}
so while (pun intended) the condition (in this case the "succesful" boolean) is false it repeats the loop I recommend reading this : http://www.tutorialspoint.com/java/java_loop_control.htm