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?
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.
In Java, the comma operator is applied only to the for loop.
In Java, the comma is a separator used to separate elements in a list in various contexts. It is not an operator and does not evaluate to the last element in the list.
Use the toLocaleString() function. var num = 1234567.89; var commas = num. toLocaleString(“en-US”);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With