What does an assignment expression evaluate to in Java?
Asked Answered
A

5

53

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?

Arborescent answered 2/7, 2016 at 19:52 Comment(0)
M
65

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.

Marder answered 2/7, 2016 at 19:56 Comment(0)
D
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...

Draughty answered 2/7, 2016 at 19:54 Comment(0)
V
9

Assignment expressions are evaluated to their assignment value.

(test = read.readLine())

>>

(test = <<return value>>)

>>

<<return value>>
Virgo answered 2/7, 2016 at 19:55 Comment(2)
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?Arborescent
@Arborescent I edited my answer to address your question about the evaluation of assignment expressions.Virgo
A
7

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.

Almswoman answered 11/10, 2019 at 7:30 Comment(0)
L
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.

Lichtenfeld answered 2/7, 2016 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.