The for loop inside the while loop will go through all the elements from the first (indexed with zero in Java) up till the last (indexed with n-1). Generally, the for loop has the same syntax as in C:
for( initial expression ; condition ; increment expression )
block
First, the initial expression is evaluated. It may contain variable declaration, as in our example. The variable j in the preceding example is visible only inside the block of the loop. After this, the condition is evaluated, and after each execution of the block, the increment expression is executed. The loop repeats so long as the condition is true. If the condition is false right after the execution of the initial expression, the loop does not execute at all. The block is a list of commands separated by semicolons and enclosed between the { and } characters.
It is ironic that the only language that strictly requires the use of the { and } braces at these places is Perl—the one language infamous for unreadable code.
The loop in the for (int j = 0; j < n - 1; j++) { sample starts from zero and goes to n-2. Writing j < n-1 is the same, in this case, as j <= n-2. We will limit j to stop in the loop before the end of the section of the array, because we reach beyond the index j by one comparing and conditionally swapping the elements indexed by j and j+1. If we went one element further, we would try to access an element of the array that does not exist, and it would cause a runtime exception. Try and modify the loop condition to j < n or j <= n-1 and you will get the following error message:
It is an important feature of Java that the runtime checks memory access and throws an exception in the case of bad array indexing. In the good old days, while coding in C, often, we faced unexplainable errors that stopped our code much later and at totally different code locations from where the real error was. Array index in C silently corrupted the memory. Java stops you as soon as you make a mistake. It follows the fail-fast approach that you also should use in your code. If something is wrong, the program should fail. No code should try to live with or overcome an error that comes from a coding error. Coding errors should be fixed before they cause even more damage.
There are also two more loop constructs in Java: the while loop and the do loop. The example contains a while loop: it is the outer loop that runs so long as there are at least two elements that may need swapping in the array:
while (n > 1) {
The general syntax and semantics of the while loop is very simple, as seen here:
while ( condition ) block
Repeat the execution of the block so long as the condition is true. If the condition is not true at the very start of the loop, then do not execute the block at all. The do loop is also similar, but it checks the condition after each execution of the block:
do block while( condition );
For some reason, programmers rarely use do loops.