• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does writeShort() use an int?  RSS feed

 
Brian Tkatch
Bartender
Posts: 598
26
Linux Notepad Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These write take their own type as input:
writeBoolean(boolean v)
writeDouble(double v)
writeFloat(float v)
writeInt(int v)
writeLong(long v)

These seem okay:
writeBytes(String s)
writeChars(String s)
writeUTF(String str)

But all these use int:
writeByte(int v)
writeChar(int v)
writeShort(int v)

Why not use byte, char, and short?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In which class are these methods?

If it's one of the standard Java classes, you might find more information about it in the API documentation.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are 8 writeShort methods in the W index to the API.
 
Brian Tkatch
Bartender
Posts: 598
26
Linux Notepad Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, still learning, i made the mistake of thinking it was obvious.
java.io.DataOutput
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are several methods like that, all in classes quite similar to DataOutput. You can find them from the link I posted earlier. Since DataOutput is actually an interface, the other seven are probably classes which implement DataOutput. There is a list of known implementing classes in the documentation for every standard Java® interface.

They are classes which divide the output into bytes; rather than writing an int in the usual fashion, they will write four bytes. In the case of DataOutput#writeShort, it takes an int, or a “narrower” integer primitive which can be “widened” to an int, but only the right half of the int is written. The two bytes are written in bigendian order.

The reason for using an int as a parameter is probably because arithmetic is done with ints, so it would be awkward to find a short around. Notice that reading the result back depends on your knowing the format of the file, and knowing that those two bytes should be read as a short in bigendian style. You can read about data streams in the Java™ Tutorials.

Why Java® supports shorts in the first place, that is a different question.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!