sunder
sunder

Reputation: 1017

What does an assignment expression evaluate to in Java?

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

Answers (5)

Mureinik
Mureinik

Reputation: 311228

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.

Upvotes: 65

Roland
Roland

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

Skurhse Rage
Skurhse Rage

Reputation: 1020

Assignment expressions are evaluated to their assignment value.

(test = read.readLine())

>>

(test = <<return value>>)

>>

<<return value>>

Upvotes: 9

nPcomp
nPcomp

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

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

Upvotes: 11

Related Questions