I encountered a statement in Java
while ((line = reader.readLine()) != null) {
out.append(line);
}
How do assignment operations return a value in Java?
The statement we are checking is line = reader.readLine()
and we compare it with null
.
Since readLine
will return a string, how exactly are we checking for null
?
The assignment operator in Java returns the assigned value (like it does, e.g., in c). So here, readLine()
will be executed, and it's return value stored in line
. That value is then checked against null
, and if it is null
, the loop will terminate.
Assignment expressions are evaluated to their assignment value.
(test = read.readLine())
>>
(test = <<return value>>)
>>
<<return value>>
(line = reader.readLine()) != null
means
- the method readLine() is invoked.
- the result is assigned to variable line,
- the new value of line will be proof against null
maybe many operations at once...
reader.readLine()
reads and returns a line for you. Here, you assigned whatever returned from that to line and check if the line variable is null or not.
来源:https://stackoverflow.com/questions/38163938/return-value-of-assignment-operation-in-java