51

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?

Michael
  • 41,989
  • 11
  • 82
  • 128
sunder
  • 968
  • 2
  • 11
  • 31

5 Answers5

63

The assignment operator in Java evaluates to the assigned value (like it does in, e.g., ). 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.

Michael
  • 41,989
  • 11
  • 82
  • 128
Mureinik
  • 297,002
  • 52
  • 306
  • 350
11

(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...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
9

Assignment expressions are evaluated to their assignment value.

(test = read.readLine())

>>

(test = <<return value>>)

>>

<<return value>>
srage
  • 990
  • 1
  • 9
  • 27
  • my question is do expressions also return something as according to you at that time (line=null), will that mean it will again return null back? – sunder Jul 02 '16 at 19:57
  • @sunder I edited my answer to address your question about the evaluation of assignment expressions. – srage Jul 02 '16 at 20:16
8

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.

Roland
  • 7,525
  • 13
  • 61
  • 124
0

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.

nPcomp
  • 8,637
  • 2
  • 54
  • 49