Why is InputStream read () returning int rather than short?

I read the byte stream and noticed the following statement

Note that read () returns an int value. If the input is a stream of bytes, why doesn't it read () returns the byte value? Using int as a return of type allows read () to use -1 to indicate that it has reached the goal of the stream.

The reason for use intis that they can identify an EOF of -1. (seems small)

So, the following is a simpler primitive type short, and it also supports -1, so why not use it?

From what I collect: (reasons to use int)

  • Due to performance intis preferred. (this)
  • intthe variable contains the character value in the last 16 bits (from the character test )
  • Other more abstract streams would have to read more than one byte (something that I think (happens with character streams))

Are my reasons true? Am I missing something (e.g. error correction)?

+4
source share
3 answers

int over short , short : , , int -typed, shortint . int.

+7

:-). , EOF, int over short, , .

StackOverflow, , Java int , short.

Java , , - - http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html. , -, , .

+1

, short : . , , , , , .

, short int. :

class A {
    short s;
    double d;
}

, :

class B {
    int s;
    double d;
}

due to alignment problems. Thus, although the first one has only 10 bytes of netto data, compared to the second one which has 12, when you select an object, it will still be bound to some 8-byte border. Even if it is just a 4-byte boundary, the memory usage will be the same.

+1
source

All Articles