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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With