By BoLOBOSE payday loan

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
}