Java Iteration

Iteration

Iteration: Repeatedly do something.

while loops

Loop

Loop executes instructions repeatedly while a condition is true.

Syntax

1
2
3
4
5
6

while( condition )
{
//statements
}

Infinite loop

  • keep going forever
  • condition always true

return statements

a return statement inside an iteration statement will halt the loop and exit the method or constructor

for loops

Syntax

1
2
3
4
5
6

for( initialization, condition, update )
{
<statements> //body of loop
}

WE MUST DECLARE THE TYPE OF THE VARIABLE MENTIONED IN INITIALIZATION!!!
This declaration can be ahead of the loop.

Off-By-One Error

check whether the code executes exactly the same times as we want

For instance, this following code have an Off-By-One Error:

1
2
3
4
5
6

String str = "for loops";
for(int i = 1, i < str.length(), i++);
System.out.print(str.substring(i,i+1));


The correct one should be:

1
2
3
4
5

String str = "for loops";
for(int i= 0, i < str.length(), i++);
System.out.print(str.substring(i,i+1))

And that’s all for this post!