8

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?

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
Aayush
  • 1,244
  • 5
  • 19
  • 48

3 Answers3

4

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.

P R
  • 105
  • 9
Mukul Goel
  • 8,387
  • 6
  • 37
  • 77
2

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.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
1

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.

Arun Kumar
  • 6,534
  • 13
  • 40
  • 67