I recently came across this syntax
int i;
String s = "test";
if(!((i=s.length()) == 0)) {
System.out.println(i);
}
If you are wondering what it prints it prints:
4
Now I know this code compiles as well as runs correctly. I also understand that this puts the value of s.length into i. I want to know how is this possible ? How can we equate/assign a variable in an if clause. Does some one have any insight not how this work with the compiler
Solved
An assignment expression
i=s.length()
resolves to the value being assigned.
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
I don't want to go get the byte code right now, but basically
- the value of of
sis pushed on the stack - that value is popped and dereferenced to invoke
String#length() - the result is pushed on the stack
- the same result is pushed on the stack again
- that value is popped from the stack and stored in
i - the value of 0 (possibly not as there might be a byte code instruction for comparison with 0) is pushed on the stack
- the value and 0 are both popped from the stack and compared, with a jump instruction depending on the result
To understand this, let's try to dissect it, statement per statement
if(!((i=s.length()) == 0))
s.length() //results to 4;
i=s.length() //assigned i=4
i=s.length() == 0 //false
!i=s.length() == 0 //invert, becomes true
if(true) {
//prints i
}
The result of a Java assignment is the value assigned, that means this
(!((i=s.length()) == 0))
Assigns s.length() to i, and then checks that that value (s.length()) is NOT 0.
The assignment operator is a ordinary expression.
Like any other expression, you can put it wherever you want to.
The value of this expression is the value being assigned. (This is also why you can write a = b = c)
Java compiler operates on sort of a stack parser where it evaluates from left to right each line. Whenever it encounters a right parenthesis the previous statement back to the last left parenthesis will be executed before anything else so...
The inner-most parenthesis will be evaluated before anything else which is of course (i=s.length()).
I'm not at my main computer right now so I can't really test this but I'm sure you'd receive a syntax error if you remove the parentheses around i=s.length().
No comments:
Post a Comment