Reputation: 1562
I have a chunk of code from a simple chat application, but that is not the important part of this question. It is the part of code which, as it seems to me, should be unreachable:
while (!end) {
outputToServer.println(consoleInput.readLine());
}
communicationSocket.close();
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
public void run() { // receiving message from other clients
String serverTextLine;
try {
while ((serverTextLine = inputFromServer.readLine()) != null) {
System.out.println(serverTextLine);
if (serverTextLine.indexOf("*** Goodbye") == 0) {
end = true;
return;
}
}
} catch (Exception e) {
}
}
What I don't understand is how will a program ever reach a part of code in which it sets "end" variable to true, when the while loop which uses it as a condition is before it... I suppose it is some basic java stuff that I don't remember, or something I persistently overlook :) Help, please?
Upvotes: 1
Views: 106
Reputation: 2177
as the code says the control will reach the line
end = true;
when the condition
serverTextLine.indexOf("*** Goodbye") == 0
returns true!,
that is the method indexOf(String) returns : the index of substring within the string if existing, and return -1 if not found!
The case to get "0" as index is only when the string starts with the substring. ie, when serverTextLine starts with "*** Goodbye".
Upvotes: 1