问题
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
?
回答1:
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.
回答2:
(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...
回答3:
Assignment expressions are evaluated to their assignment value.
(test = read.readLine())
>>
(test = <<return value>>)
>>
<<return value>>
回答4:
The Java® Language Specification 15.26. Assignment Operators
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.
回答5:
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