0

As I know, there is good practice use int variables for arithmetical operations. Because, if we use "byte" or short JVM regardless cast it to int in arithmetical operations.

So, I want to ask, where programmers employ byte and short in Java.

P.S. Schildt in his book say that byte can be "useful when you're working with a stream of data from a network or file". But I can't find any example's.

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
  • 1
    A key difference is the actual size in memory. A byte is 1 byte. A short is already two bytes and an int is 4 bytes. Depending on what size of data you want to save, you use the most suitable type. Especially in an embedded environment, where memory is limited. Please see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html for further information. – Korashen Oct 24 '18 at 09:06
  • You could use it for constants. For example: `public static final byte BLOCKS_AMOUNT = 3;` – Valentin Grégoire Oct 24 '18 at 09:13
  • I would look in the java.io or java.nio packages or any code which uses them. You should be able to find millions of examples. – Peter Lawrey Oct 24 '18 at 11:05

2 Answers2

0

You can use them to save memory, since int is 32-bit signed, byte is 8-bit signed and short is 16-bit signed. In cases where you have a large amount of these items, and you know the maximum value will fit in the data type you chose you're saving memory.

For example int test = 1; will still take up 32 bits of memory while it's contents would also fit in a byte

Mark
  • 5,089
  • 2
  • 20
  • 31
  • 1
    Overheads depends on platform, but the primitive size is constant, see https://stackoverflow.com/questions/229886/size-of-a-byte-in-memory-java – Ryan Leach Oct 24 '18 at 09:08
0

If you wanna change some data in binary file , maybe you need byte. As a high-level language , memory useage is not a problem , best practice is if you don't know what you should to use , just int , like tcp.

winters
  • 96
  • 1
  • 4