-2
String var;
while((var = "abc") == "abc"){ 
    System.out.println("In loop"); 
}

What is the advantage of assigning a variable while doing a check for the condition in the while loop.

jhamon
  • 3,603
  • 4
  • 26
  • 37
Dasarathan
  • 63
  • 5

1 Answers1

7

In that example, there is none, but I assume you're talking about something like:

while ((var = obj.someMethod()) != null) {
    // ...use var...
}

...where null is any of several marker values depending on what obj and someMethod are. For instance, using BufferedReader's readLine, you might loop through lines like this:

while ((line = reader.nextLine()) != null) {
    // ...use the line...
}

This is a fairly common idiom when dealing with objects that have a method that keeps returning something useful until/unless it reaches the "end" of what it's working through, at which point it returns a marker value saying it's done (null is a common choice). The idiom is useful because it advances to the "next" thing, remembers the "next" thing, and checks for whether it's done.

But in your example, there'd be no point whatsoever. Also, it compares strings incorrectly. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Your explanation is fairly enhance my ask. However, out of curiosity, wouldn't it be simple to code like this. what would be wrong in this approach while ((reader.nextLine()) != null) { // ...use the line... } – Dasarathan Jan 30 '19 at 13:18
  • @Dasarathan - How would you `...use the line...` if you don't have it? `BufferedReader` doesn't have a `getLastLine` or similar method. Keeping track if the line it just gave you is *your* task. :-) – T.J. Crowder Jan 30 '19 at 13:18
  • 1
    @t-j-crowder Ok got it. Helpful. – Dasarathan Jan 30 '19 at 13:20