Java, System.out.println() with an assignment inside
I just noticed that you can do System.out.println(FooObject.fooNumber = 4);
which will assign 4 to fooNumber and also output the value 4. Why does it output FooNumber after the assignment?
Also, the rules of precedence state that the assignment occurs first but nothing about whether the print occurs first or the assignment. Am I right? So why doesn't the previous value get printed first and then the assignment? As I know, subexpressions are evaluated left to rig开发者_StackOverflow社区ht in Java, so does this apply here?
This is valid Java syntax, to do an assignment statement inline, which then returns the assigned value. A common example of using this syntax is with reading a file:
while ((str = in.readLine()) != null) {
process(str);
}
It's because expressions like a = b
have type of a
and value of a
, after assignment. This statement is recursive, so a = b = c
and others are also the same.
Yes you can do that pretty much everywhere, which in fact will assign the value to fooNumber
, it can be rather annoying since usually you don't want to assign something but compare it with double ==, and can be an easy thing to miss.
It will output fooNumber
because it will assign it first then display its value.
try: int x = FooObject.fooNumber = 4
.
x
will get the value 4 as well, in java, the operator=, is being reflected backward, and the evaluation is from right to left, so the same applies here, and the value passed to println()
will be 4.
your command is actually equivalent to:
FooObject.fooNumber = 4;
int temp = FooObject.fooNumber;
System.out.println(temp);
精彩评论