Search code examples
javaio

What is difference between first while loop and second while loop?


what is difference between 1st and 2nd loop;

package standard;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class practice {
    public static void main(String args[]) throws IOException
        {
    FileInputStream f=new FileInputStream("F:\\a.txt"); 

its 1st while loop which has a int in it

    int s;
    while((s=f.read())!=-1)
    {
        System.out.print((char)s);
    }

this is 2nd while loop

    while(f.read()!=-1)
        {
        System.out.print((char)f.read());
        }
     }



}

Solution

  • The first while loop reads a byte into a variable in the loop's condition and checks that's it's not equal to -1, and then prints that variable in the loop body.

    The second while loop reads a byte, checks that it's not equal to -1, and then reads the next byte in the loop's body and prints it.

    Therefore the first loop prints the entire file while the second loop prints half the bytes of the file.