Csi
Csi

Reputation: 526

What does this condition do (BufferredReader and InputStreamReader)?

I'm currently reading a code and i found a method starting like this :

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));  

String userInput;

while ((userInput = stdIn.readLine()) != null) {

  }

Can someone explain me the condition while ? That a = b != c seems weird to me.

Upvotes: 2

Views: 186

Answers (4)

Sonu Gupta
Sonu Gupta

Reputation: 367

It is something like:

int a = 0;
int b = 0;

while ((a = b++) != 10) {

    System.out.println(a);

};  

Here we are assigning a with increment of b, and checking whether its value is 10 or not.

Same way, userInput = stdIn.readLine() means we are reading a line, assign it to userInput variable and checking until it reads null.

Upvotes: 1

Brian
Brian

Reputation: 15740

= is an assignment operator, not a comparison operator.

(a = b) != c assigns b's value to a, and then compares it to c.

In the case of

while ((userInput = stdIn.readLine()) != null) { ... }

stdIn.readLine() is getting a value, which is then stored as userInput, and that value is checked to make sure it isn't null in order for the while loop to progress. This results in the loop reading each line of the file until it runs out of lines to read.

Upvotes: 1

CubeJockey
CubeJockey

Reputation: 2219

Seems like your eyes are glancing over a pair of parentheses:

while ( (userInput = stdIn.readLine() ) != null) {

}

I've attempted to make it more clear above.

The variable userInput is being assigned stdIn.readLine(). And while userInput isn't null following that assignment, the loop continues.

It's just a one-liner for handling the userInput update, as well as checking for null

Upvotes: 2

Forketyfork
Forketyfork

Reputation: 7810

The assignment in brackets (userInput = stdIn.readLine()) does two things at once: it assigns the line to userInput variable and evaluates itself to this value. But if nothing was read, the readLine() returns null, and whole expression evaluates to null.

So while there are lines in the user input, the condition (userInput = stdIn.readLine() ) != null holds, and the while loop continues. When there are no more lines in the user input, the condition is false, and the while loop stops.

Upvotes: 1

Related Questions