The Infinte For Loop – Java

The infinite for loop is rather similar to the standard infinite while loop. The while loop uses true as an argument and will continue to operate forever because the argument is true and will not change. Similarly the infinite for loop works almost the exact same way. It uses true as it’s boolean expression and just leaves the initialization as null and the stepper as null. It looks like this.

1
2
3
4
5
6
7
8
9
10
//creating an infinite loop by making the boolean value true and the other expressions null.
for(; true ;){
    System.out.println("Test");
}
 
//similar to this there is the while loop.
while(true){
    //The expression just needs to be true.
    //for example, it could be while(5 > 2){...
}

The Comma Operator in Java

Java has an often look past feature within it’s for loop and this is the comma operator. Usually when people think about commas in the java language they think of a way to split up arguments within a functions parameters. ie:

1
2
3
private static void toast(int temp, int duration){
System.out.println("That is some nice toast!");
}

The comma operator can be used in two sections of the for loop. First we need to look at a for loop and identify what each section is and does.

1
2
3
for(int x = 0; x <= 10; x++){
System.out.println("nom");
}

The first part where we declared x as 0 is known as the initialization, the second part where we say that x <= 10 is the boolean or sometimes known as the expression, the last part is known as the step or increment.

The first part of the for loop that we can apply our comma operator to is the initialization and the second part of the loop that we can apply it to is the incrementing part. Because the expression needs to equate to a booleon we cannot use the comma operator here.

Note: The comma operator will only work if the data types declared are of the same type. ie: integer.

Here is an example of a for loop using the comma operator.

1
2
3
for(int x = 1, int z = 9; z &lt;= 923; z++, x += 2){
    //statements
}