Java - comma operator outside for loop declaration

JohnEye picture JohnEye · Sep 26, 2012 · Viewed 10k times · Source

I know I can use the comma operator like this

for (int i = 1, j = 15; j>10; i++, j--) {
    // do something neat
}

but some articles seem to suggest that the comma operator can be used outside of the for loop declaration, for example

int j = 2, k = 4 ;
int x ;
// Assignment statement with comma operator
x = j + 1, k ;

source: http://www.cs.umd.edu/~clin/MoreJava/ControlFlow/comma.html

or

int x = (expression) ? (i++,2) : 3;

source: https://stackoverflow.com/a/12047433/1084813

This would be a neat trick for a code obfuscation contest or to confuse my colleagues, but neither of the examples will compile (Java 1.6, Eclipse Juno), the error is "The left-hand side of an assignment must be a variable". I tried looking at the compiler settings to see whether it could be forbidden to prevent bad code, but without luck.

What's wrong? Was the comma operator a part of an older specification which later changed? Are the people that wrote those examples using a different Java setup that allows this?

Answer

18446744073709551615 picture 18446744073709551615 · Dec 10, 2013

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.27

15.27. Expression

<...>

Unlike C and C++, the Java programming language has no comma operator.