Saturday, April 15, 2023

Difference between ByteBuffer vs byte array in Java? Example Tutorial

There are several differences between a byte array and ByteBuffer class in Java, but the most important of them is that bytes from byte array always reside in Java heap space, but bytes in a ByteBuffer may potentially reside outside of the Java heap in case of direct byte buffer and memory mapped files. Buffer is a byte array like abstraction which was introduced in Java NIO release to read and write data from FileChannel. It is extensively used in Java NIO for transferring data from one place to another and its also an essential Java concepts to know for any backend developer, particularly those who wants to create non-blocking server application using NIO in Java



Difference between a Byte array and ByteBuffer in Java

What is the difference between a ByteBuffer and Byte array is also a popular Java interview questions. Knowing and remembering the difference can also help you to do well on Java interviews. Here are a couple of more key differences between byte arrays and ByteBuffer in Java:

1. Comparison using equals()

You cannot compare byte array using equals() and hashCode(), you need to use Arrays.equals() and Arrays.deepEquals() method but you can compare two ByteBuffer using those two methods.

2. Byte Order (Big Endian and Little Endian)

ByteBuffer allows you to read and write data in any byte order like both little-endian and big-endian. Big Endian is also known as network byte order.

Difference between byte array and ByteBuffer in Java



3. Copy

ByteBuffer has a unique capability to pass a subset of a byte buffer as a value without copying the bytes, by instantiating a new ByteBuffer.
  • The NIO API makes extensive use of ByteBuffer:s.
  • The bytes in a ByteBuffer may potentially reside outside of the Java heap.
  • A ByteBuffer has a state beyond the bytes themselves, which facilitates relative I/O operations (but with caveats, talked about below).
  • A ByteBuffer offers methods for reading and writing various primitive types like integers and longs (and can do it in different byte orders).

4. Mutability

A byte array is a mutable in Java, which means its elements can be changed after creation but ByteByffer class is immutable in Java, although its content can be modified


5. Writing

Byte array doesn't provide any specific method to write a particularly data type but ByteBuffer provides different methods to write different data types into buffer like putInt(), putDouble(), putChar() and getInt(), getDouble() and getChar() methods. There are many more methods to support all Java data types.  


6. Capacity

A byte array has a fixed capacity which means you cannot change the capacity of byte array once created but ByteBuffer has dynamic capacity and you can increase decrease the capacity after creation and depending upon data.

Difference between byte array and ByteBuffer in Java



7. Concurrency and Thread safety

Byte array is not thread-safe hence its not suitable for use in a multi-threaded and concurrent environment but ByteBuffer provide thread safe access  to its accessor methods which makes it a better choice in concurrent Java application.

8. Easy to work with Binary data

Byte array doesn't provide any utility method you can just save and get data from index but ByteBuffer provides various methods to deal with different data types which makes it easier to deal with binary data .

9. Access to Memory Outside JVM

Many people doesn't know but you can create direct byte buffer in Java which can represent memory outside the heap, for example MemoryMappedBuffer which is a subclass of DirectBuffer and provide access to memory mapped file in Java. 


10. Byte array and ByteBuffer Example in Java

Here's an example of creating and manipulating a byte array in Java:

byte[] byteArray = new byte[5];
byteArray[0] = 1;
byteArray[1] = 2;
byteArray[2] = 3;
byteArray[3] = 4;
byteArray[4] = 5;

System.out.println("Byte Array: " + Arrays.toString(byteArray));

And here's an example of creating and manipulating a ByteBuffer in Java:

ByteBuffer byteBuffer = ByteBuffer.allocate(5);
byteBuffer.put((byte) 1);
byteBuffer.put((byte) 2);
byteBuffer.put((byte) 3);
byteBuffer.put((byte) 4);
byteBuffer.put((byte) 5);

System.out.println("Byte Buffer: " + Arrays.toString(byteBuffer.array()));

You can also use methods like putInt() and putLong() to directly put integer and long in ByteBuffer in Java as shown below:

ByteBuffer buffer = ByteBuffer.allocate(100);
buffer.putInt(100);
buffer.putLong(200L);
buffer.flip();

System.out.println("Int value: " + buffer.getInt());
System.out.println("Long value: " + buffer.getLong());


Here is the output of the code, which will be printed on Console:

Int value: 100
Long value: 200


That's all about the difference between ByteBuffer and Byte array in Java. You can use ByteBuffer when you use FileChannel to read data from a Socket or File in Java and byte array for normal IO and dealing with InputStream and OutputStream. Channel also allows you to perform non-blocking read in Java. 

Other Java IO tutorials you may like:
  • How to read CSV files in Java? (program)
  • How to convert ByteBuffer to String in Java? (example)
  • How to append data into an existing file in Java? (answer)
  • How to read the file in one line in Java 8? (solution)
  • How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory in Java (solution)
  • How to read the file line by line in Java using BufferedReader and Scanner? (answer)
  • How to read/write an Excel file in Java? (program)

Thanks for reading this article so far. If you like this Java ByteBuffer vs Array Tutorial  then please share with your friends and colleagues. If you have any questions or feedback, please ask. 

1 comment :

Anonymous said...

Nice tutorial

Post a Comment