Buggy Example Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

The sum is: 255

Buggy Example Program

Here is a program that reads two 8-byte longs. The previous program reads four 4-byte ints. This new program uses the same data file as the previous.

import java.io.*;
class ReadLongs
{
 public static void main ( String[] args ) 
 {
   String fileName = "intData.dat" ;   long sum = 0;

   try
   {      
     DataInputStream instr = 
       new DataInputStream(
         new BufferedInputStream(
           new FileInputStream( fileName  ) ) );

     sum += instr.readLong();
     sum += instr.readLong();
     System.out.println( "The sum is: " + sum );
     instr.close();
   }
   catch ( IOException iox )
   {
     System.out.println("Problem reading " + fileName );
   }
 }
}

Here is a sample run:

C:/Programs>java  ReadLongs
The sum is: 1099511627776

C:/Programs>

The program used the same input file and read the same bits as the previous program, but computed a different answer. What happened? Well, this program read the first 8 bytes of the file as a long value. But when those 8 bytes were written, they were intended to be two 4-byte ints. Then the second 8 bytes were read as another long value. But they, also, were intended to be two ints. In other words, the new program interpreted the bytes of the file incorrectly. No wonder it computed a strange answer!

QUESTION 4:

Could the program be written so that it checks for valid input?