Using byte arrays in java

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.

Читайте также:  String formatting examples in python

3. Copy

  • 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.

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.

Читайте также:  Index html listing files

10. Byte array and ByteBuffer Example 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));
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()); 
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.

  • 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)

Источник

How to Initialize a Byte Array in Java?

In this tutorial, we will learn how to initialize a byte array in Java.

What is a byte?

We all know that 8 bits = 1 byte or we can say a combination of eight zeros and ones. A byte represents a sort of digital information or data in binary format.

Byte in Java

A byte in Java is one of the primitive data types. It means, a byte stores the same size as that of computer memory.
If you look at some primitive data types in Java, you will see a byte stores values ranging from -128 to +127. That means we can store the values only from -128 to 127 and if we want some value greater than this range, then we can simply use datatype conversion.

Читайте также:  Java массив это ссылка

Byte Array in Java

As we have seen, a byte is a combination of eight zeros and ones.
A byte array is a combination of bytes values. It means if you want to load some content directly into the memory then this can be helpful.

How to Initialize a byte array in Java?

Now, there are many ways in which we can initialize a byte array. Examples are given below:

public static void main(String[] args)< // Declaration of byte array byte[] myfirstarray = new byte[10]; >
public static void main(String[] args)< // Declaration of byte array byte myfirstarray[] = new byte[10]; >

When you assign memory to a byte array, initially the default value is zero. This is not only in byte array but also in all the arrays in Java. There is always some initial value allocated to every array.

Assigning Elements to byte array in Java

In Java, we assign elements to the Java array by indexing only.
An example is given below:

public static void main(String[] args) < // declaration of byte array byte[] values = new byte[5]; // Assigning elements values[0] = 12; values[1] = 10; values[2] = 75; values[3] = 40; values[4] = 101; // printing byte elements for(int i=0;i>

In this example, you can see, we have declared an array for byte with the size of 5. Then we have assigned values to it with the help of indexing. And printing all values with the help of for-loop iteration.
The output:

Element at 0: 12 Element at 1: 10 Element at 2: 75 Element at 3: 40 Element at 4: 101

Источник

Оцените статью