Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - comma operator outside for loop declaration

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?

like image 544
JohnEye Avatar asked Sep 26 '12 12:09

JohnEye


People also ask

Can I use comma in for loop?

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 which type of loop the comma operator can be used in Java?

In Java, the comma operator is applied only to the for loop.

Does Java have a comma operator?

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.

How do you add a comma to a variable in Java?

Use the toLocaleString() function. var num = 1234567.89; var commas = num. toLocaleString(“en-US”);


1 Answers

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.

like image 114
18446744073709551615 Avatar answered Oct 14 '22 23:10

18446744073709551615