Java 11 Developer Certification - Java Loop Structures
October 25, 2020
What we are covering in this lesson
- What is a loop
- Types of loop in java
- Loop Syntax
- Code examples
What is a loop
A loop causes a set of instructions to execute repeatedly, until a certain condition is met, or the element list being looped through is exhausted. Loops are very fundamental to programming.
Types of loop in java
Java supports 3 types of loops statements
for
loopwhile
loopdo while
loop
while
and do while
loops are quite similar in nature, the only difference being that do while
will always execute atleast once before checking the condition in while.
while
loop keeps executing until the conditions are met, and the iteration counters are done within the code block.
for
loop is mostly used when the number of iterations needed are known beforehand.
Loop Syntax
while loop Syntax
while (expression) {
statement1;
statement2;
statementn;
}
do while loop syntax
do {
statement1;
statement2;
statementn;
} while (expression);
for loop syntax
//traditional for loop
for (initialization; termination condition; increment/decrement) {
statement1;
statement2;
statementn;
}
OR
//advanced for loop
for (formalParameter : expression) {
statement1;
statement2;
statementn;
}
Code examples
Lets have a look at a simple code snippet to understand these loops and the basic difference between them.
package maxCode.online.Loops;
public class WhileDoWhileLoops {
public static void main(String[] args) {
// set up a boolean that while be the condition for our while loop
boolean isTrue = true;
int iterations = 0;
while (isTrue) {
//if (++iterations > 2) break;
//if (iterations == 2) continue;
if (++iterations > 2) {
isTrue = false;
}
System.out.println("Iteration: " + iterations + ", isTrue = " + isTrue);
//Nested do while loop
do {
System.out.println("Do while start," + " iteration = " + iterations);
System.out.println("Do while end");
} while (iterations < 0);
} // end while
}
}
Output
Iteration: 1, isTrue = true
Do while start, iteration = 1
Do while end
Iteration: 2, isTrue = true
Do while start, iteration = 2
Do while end
Iteration: 3, isTrue = false
Do while start, iteration = 3
Do while end
The above code clearly indicates that the while
loop keeps on executing until the condition isTrue
remains true. As soon as it is false, the next loop does not execute.
Also, keep in mind that the line where this condition is made false. The lines below that will also get executed and it only in the next loop condition when the condition will be evaluated false.
The condition variable isTrue
needs to be manipulated within the loop only, such that the statements execute for as much time as we want.
The do while
loop always executes only once because the condition we have specified will never stand true.
Unlike while
, it will always execute once regardless of the condition.
In case of for
loop, we have 2 types of loop. One is the basic traditional for
loop and the other one is a advanced loop.
The tradional one has a initialization expression, termination condition and increment/decrement and all these are separated by semi-colon.
The init expression initializes the for loop, only executed once when the loop begins, prior to the termination condition being evaluated for the first time. It is optional.
The termination condition specifies the condition till when the loop must run. As soon as this condition is false, the loop terminates. This expression is also optional and its default value is true. It is evaluated prior to each loop iteration.
The increment/decrement value is invoked after each iteration of the loop. This is also optional.
As you can see, all the 3 parameters are optional, so if we have a for (;;)
, it will create an infinite loop, and anything within it will execute forever!
The advanced for loop is used to loop through an iterable set of data and so some operation. The type of expression must be iterable or an array type. If we want an iterator index in advanced loop, we have to create and maintain it ourselves.
package maxCode.online.Loops;
public class ForLoop {
public static void main(String[] args) {
System.out.println("----------- TRADITIONAL FOR LOOP -----------");
String[] strArray = {"1", "2", "3"};
for (int i = 0; i < strArray.length; i++) {
System.out.println("Argument " + (i + 1) + " = " + strArray[i]);
}
System.out.println("----------- ENHANCED FOR LOOP -----------");
int i = 0; //iterator index, you have to maintain it yourself
for (String arg: strArray) {
System.out.println("Argument " + (++i) + " = " + arg);
}
}
}
Output
----------- TRADITIONAL FOR LOOP -----------
Argument 1 = 1
Argument 2 = 2
Argument 3 = 3
----------- ENHANCED FOR LOOP -----------
Argument 1 = 1
Argument 2 = 2
Argument 3 = 3
Note:
loop
is not a reserved word.- Any loop can have a break in it, usually a conditional break.
- Any loop can also have a continue statement in it, also usually conditional.
- Statements after the continue statement are skipped until the next iteration.
- Infinite loop can be created by
for (;;);
- We cannot reference a label with the continue, or break statements that is not in the loops scope, else it gives a compiler error.
- An outer loop cannot reference the inner loop’s labels, but an inner loop can reference the outer loop’s labels.
- You can break out of a nested loop from a nested loop.
- You can also completely break out of the parent loop, from the nested loop.
Thats it for loops. Keep trying different permutations in loops, like using increment/decrement operator, or throwing exception during init, and explore the different ways loops work!