boxed__l
boxed__l

Reputation: 1336

Why does InputStream read() return an int and not a short?

I was reading the byte stream trial and noticed the following statement

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

The given reason for using an int is that they can identify EOF by a -1. (seems shallow)

So the next bigger primitive type is short and it also supports -1 so why not use it?

From what i gather: (reasons to use int)

  1. Due to performance int is preferred. (this)
  2. int variable holds a character value in its last 16 bits (from character trial)
  3. Other more abstract streams would need to read more than just one byte (something that i guess (happens with character streams))

Are my reasons correct? Am i missing something (like error correction)?

Upvotes: 6

Views: 667

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200168

The most important reason to prefer int over short is that short is kind of a second-class citizen: all integer literals, as well as all arithmetical operations, are int-typed so you've got short->int promotion happening all over the place. Plus there is very little or no argument against the usage of int.

Upvotes: 8

Martin Zikmund
Martin Zikmund

Reputation: 39082

This is an interesting question :-) . It is true, that they had to use signed integer value type to represent EOF, but the preference of int over short is probably really just performance.

As I found on a different StackOverflow thread where this was discussed, the Java VM would automatically use int internally even if the definition used short.

The Java documentation states, that short should be used in large arrays and situations where memory really matters - source - http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html . That is apparently no the case here, because we always get just one value.

Upvotes: 1

Ingo
Ingo

Reputation: 36339

There is only one scenario where using short will give you an advantage: large arrays of short. To be sure, you can use them only when it is clear that the numbers to be stored fit the bounds.

In all other cases, it makes no real difference whether you have short or int. For example:

class A {
    short s;
    double d;
}

will not use less memory than:

class B {
    int s;
    double d;
}

because of alignment issues. So while the first one only has 10 bytes netto data, as compared to the second one that has 12, when you allocate an object it will still get aligned to some 8-byte boundary. Even if it is only a 4 byte boundary, the memory usage will be the same.

Upvotes: 1

Related Questions