Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this while loop know when to fail?

I was reading about how to program network sockets and ran across this piece of code:

try {     
   while (true) {   // This is the line in question
     int i = in.read(  );
     if (i == -1) break;
     System.out.write(i);
   }
 }
 catch (SocketException e) {
   // output thread closed the socket
 }
 catch (IOException e) {
   System.err.println(e);
 }

How does the second line know when to fail? In other words, how does the while(true) loop work? I guess I don't understand 'While what is true?'

like image 688
hax0r_n_code Avatar asked Mar 24 '23 15:03

hax0r_n_code


1 Answers

The important line here is:

if (i == -1) break;

The break will exit the current loop when i == -1. Without this line it would be an infinite loop.

like image 174
Shafik Yaghmour Avatar answered Apr 06 '23 07:04

Shafik Yaghmour