Search code examples
javacomma-operator

Java's comma separator - does it force an evaluation order?


I'm writing a loop to make multiple fragments out of a byte array, where the first fragment must be a different size from later fragments.

for (int frag_start = 0, frag_end = Math.min(len, MAX_FIRST_FRAG_SIZE);
     frag_start < len;
     frag_start = frag_end, frag_end = Math.min(len, frag_start + MAX_LATER_FRAG_SIZE)) {
     // code goes here
}

Does the comma in frag_start = frag_end, frag_end = ... enforce that the assignment, before the comma, will always happen ahead of the assignment after the comma, or is the JVM free to reorder those operations?


Solution

  • In Java, the evaluation of expressions separated by the comma operator , is strictly from left to right. Each expression within a comma is evaluated fully before moving to the next one.

    Note that the comma operator has the lowest precedence of any operator.