Return value of assignment operation in Java

旧巷老猫 提交于 2019-11-26 03:59:33

问题


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

  1. the method readLine() is invoked.
  2. the result is assigned to variable line,
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!