The basis of for and while loops in Java are similar to most programming languages. First the loops type is called, parameters are applied, a block of statements are executed based on the parameters then finally the loop is closed off.
For Loop
The basis of the for loops is as follows:
1 2 3 4 | for(Set of Parameters) { //opening the block Block of statements to be executed. } //closing the block |
An example of the for loop will look something like this:
1 2 3 | for (int a = 0; a <= 5; a++) { System.out.println("integer a = " + a ) } |
While Loop
Now we are going to show the basic outline of the while loop.
1 2 3 4 | while(True or False statement, Boolean value) { Statement to be executed. } |
Do While
It is also possible to switch the statements around to create a do-while statement. This statement follows the while statements format except it switches around the while parameters and the block statements. It looks something like this:
1 2 3 | do { These statements while } while (this Boolean value is true or false.) |
These loops are quite simple to execute and easy to work with. The block statements can be replaced with other loops that are nested.