Reputation: 1017
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
?
Upvotes: 54
Views: 26563
Reputation: 311228
The assignment operator in Java evaluates to the assigned value (like it does in, e.g., c). So here, readLine()
will be executed, and its return value stored in line
. That stored value is then checked against null
, and if it's null
then the loop will terminate.
Upvotes: 65
Reputation: 7853
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.
Upvotes: 7
Reputation: 1020
Assignment expressions are evaluated to their assignment value.
(test = read.readLine())
>>
(test = <<return value>>)
>>
<<return value>>
Upvotes: 9
Reputation: 9843
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.
Upvotes: 0
Reputation: 48258
(line = reader.readLine()) != null
means
maybe many operations at once...
Upvotes: 11