Besides the fact that bytes saves memory by consuming only eight bits of storage as against 32bits for integer
. What other practical uses does it serve? I read in a text that it is useful when we are working with stream of data from a network or a file. They are also useful when you're working with raw binary data that may not be directly compatible with Java's other built-in types. Could any one explain these with examples? and state a few more practical uses?

- 40,646
- 13
- 77
- 103

- 1,244
- 5
- 19
- 48
-
All network and disk APIs work in byte units. Hadn't you noticed? – user207421 Sep 28 '12 at 07:40
3 Answers
As u read, bytes are useful when reading stream of bits
Before telling the reason, lemme ask you a question how many bits or bytes a character is represented as ?? 8bits/1byte. I hope here you got the reason of byte.
The reason of using byte when reading stream of bits is that when u read the stream in a byte, each time u read, u will have one byte of data in your byte type variable. I.e. 1 character. Thus while reading you will get a character at a time.
Also machines understand bits, so byte come in handy there as well, when reading from any input like keyboard,file,data stream etc we prefer byte. Similarly when writing to devices monitors , output stream, files , etc byte comes in handy.
also everything around is multiples of 10100010 , so when you are not sure what to expect from sender or what the receiver expects, use byte.

- 105
- 9

- 8,387
- 6
- 37
- 77
-
-
@RadijatoR: I meant that everything is made up of bytes (there are 8 bits in 10100010) – Mukul Goel Aug 24 '15 at 16:28
Usually byte arrays are used for serialization (to disk, network stream, memory stream, etc). A simple example of this could be something like so (taken from here):
Object object = new javax.swing.JButton("push me");
try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}
Another usage of the byte datatype is also related to images. For instance you could do something like so: byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
(taken from here) to access pixel related information.
byte
is a 8-bit signed primitive-type in java. It is usefull in the situations where we are dealing with the data in the form of bytes such as "Reading/writing the byte data from/to files".
You can find the best practical example at here.

- 6,534
- 13
- 40
- 67