ross studtman
ross studtman

Reputation: 956

Why cast an int to byte in BufferedOutputStream write method that takes an int argument?

In "Introduction to Java Programming," 9th ed, by Y. Daniel Liang, in chapter 19 about binary IO is written a code example where the write() method casts an int to a byte. Why?

For example:

    /*
     *  Read and write bytes.
     */
    int intByte = 0;

    int numberOfBytesCopied = 0;

    while( (intByte = bufferedInputStream.read()) != -1){

        bufferedOutputStream.write((byte)intByte);

        numberOfBytesCopied ++;
    }

Java Documentation indicates three overloaded write methods: one takes a byte array, the other takes a byte array (allowing for start and end points to be designated), the other takes an int.

Why does the text cast intByte above to a byte? And by making that cast I don't see a write method that takes a single byte? Since the program runs without error, is the int-cast-to-a-byte being recast to an int by JVM? Or is the lonely byte being converted by the JVM to an array with a single element to satisfy the write parameter? Or?

I coded the example and ran it with the cast and without the cast, both run without incident. So I'm tempted to do away with the cast but figure there's a reason for it I don't understand.

Upvotes: 3

Views: 1357

Answers (3)

Morteza Adi
Morteza Adi

Reputation: 2473

The cast doesn't matter here since fortunately in the BufferedOutputStream.write() method cast will happen.

public synchronized void write(int b) throws IOException {
    if (count >= buf.length) {
        flushBuffer();
    }
    buf[count++] = (byte)b;
}

as documentation says the method only writes 8 first bit and the rest will be ignored. this is the effect of casting int type to byte.

I think the author put the cast to clarify what is going to write into output! this way the unaware developers don't need to consult JavaDoc to see what will be written to output!

It is always good practice to clarify your code as much as possible.

P.S: code runs as folows intByte will cast to byte then because of effect of widening write(int) method will be called and the rest...

Upvotes: 3

Richard Lewan
Richard Lewan

Reputation: 232

By casting the intByte to a byte, the value is narrowed from 32-bit to 8-bit. The write() method can accept a byte even though its signature asks for an int -- this is called widening (no cast required). That part is inconsequential. But the cast from int to byte is important since it could dramatically affect the value of the variable by trimming off the leading 24 bits. Try this, for example, and see what happens:

int i = 13465878; byte b = (byte)i; System.out.println("i as a byte is " + b);

Upvotes: 2

Henry
Henry

Reputation: 43758

Technically there is no reason for the cast. Maybe the author thought the program is clearer if the cast is included.

Upvotes: 3

Related Questions