Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Convert byte[] to Byte[] and Vice Versa in Java

$
0
0

1. Overview

While Byte is a wrapper of the primitive byte, and the conversion can be done automatically by autoboxing for individual values, it’s important to note that this automatic conversion doesn’t extend to arrays. In this article, we’ll dive into the different approaches to converting byte arrays to Byte arrays and vice versa in Java.

2. Dependencies

To demonstrate one of the converting approaches, we’ll use the Apache Commons Lang library. Let’s add its dependency to our bytepom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

3. Byte.valueOf()  and byteValue() 

The first approach we’ll explore is to use Byte.valueOf() and a byteValue() of a Byte object in a loop.

3.1. Byte.valueOf()

Byte.valueOf(byte b) returns a Byte instance with a byte value sent in the input parameter of this method.

Let’s convert each byte in the array into a wrapper object using Byte.valueOf(byte b) and iterating the array in a loop:

private static final byte[] PRIMITIVE_BYTE_ARRAY = {65, 66, 67, 68};
private static final Byte[] EXPECTED_ARRAY_VALUES = {65, 66, 67, 68};
@Test
void givenPrimitiveByteArray_whenConvertingUsingByteValueOf_thenGiveExpectedResult() {
    Byte[] newByteArray = new Byte[PRIMITIVE_BYTE_ARRAY.length];
    for (int i = 0; i < PRIMITIVE_BYTE_ARRAY.length; i++) {
        newByteArray[i] = Byte.valueOf(PRIMITIVE_BYTE_ARRAY[i]);
    }
    Assertions.assertThat(newByteArray)
      .containsExactly(EXPECTED_ARRAY_VALUES);
}

As we can see, all the bytes were copied into new Byte[], and all the values remain in the same places.

3.2. Byte.byteValue()

The byteValue() of a Byte object returns a primitive byte value inside it. Let’s iterate the Byte[] and call this method for each element:

private static final byte[] EXPECTED_ARRAY_VALUES = {65, 66, 67, 68};
private static final Byte[] BYTE_ARRAY = {65, 66, 67, 68};
@Test
void givenByteArray_whenConvertingUsingByteValue_thenGiveExpectedResult() {
    byte[] newByteArray = new byte[BYTE_ARRAY.length];
    for (int i = 0; i < BYTE_ARRAY.length; i++) {
        newByteArray[i] = BYTE_ARRAY[i].byteValue();
    }
    Assertions.assertThat(newByteArray)
      .containsExactly(EXPECTED_ARRAY_VALUES);
}

As expected, we copied the bytes into the primitive array using unboxing.

4. Autoboxing and Unboxing

We can rewrite the code above in a more straightforward way using autoboxing to convert a byte value into a Byte instance and vice versa, utilizing unboxing.

If we disassemble our next code fragments – we can use the javap tool for this purpose – we’ll see that autoboxing calls the Byte.valueOf() method, while unboxing calls byteValue() of a Byte object under the hood. Therefore, technically, it’s the same logic with less code.

4.1. Autoboxing

Let’s convert each byte in the array into a wrapper object using autoboxing and iterating the array in a loop:

@Test
void givenPrimitiveIntArray_whenConvertingAutoboxing_thenGiveExpectedResult() {
    Byte[] newByteArray = new Byte[PRIMITIVE_BYTE_ARRAY.length];
    for (int i = 0; i < PRIMITIVE_BYTE_ARRAY.length; i++) {
        newByteArray[i] = PRIMITIVE_BYTE_ARRAY[i];
    }
    Assertions.assertThat(newByteArray)
      .containsExactly(EXPECTED_ARRAY_VALUES);
}

As we can see, all the bytes were copied into new Byte[], and all the values remain in the same places.

4.2. Unboxing

Now, we’ll perform the opposite operation and convert Byte[] into its primitive analog:

@Test
void givenByteArray_whenConvertingUsingUnboxing_thenGiveExpectedResult() {
    byte[] newByteArray = new byte[BYTE_ARRAY.length];
    for (int i = 0; i < BYTE_ARRAY.length; i++) {
        newByteArray[i] = BYTE_ARRAY[i];
    }
    Assertions.assertThat(newByteArray)
      .containsExactly(EXPECTED_ARRAY_VALUES);
}

As expected, we copied the bytes into the primitive array using unboxing.

5. Arrays.setAll()

Since Java 8, we can simplify our code using Arrays.setAll(T[] array, IntFunction<? extends T> generator) instead of a loop. In the first parameter, we’ll send our target array, while in the second parameter, we will have a function that sets a new value for each element.

Let’s rewrite our code for converting byte primitives array into Byte objects array using Arrays.setAll():

@Test
void givenPrimitiveByteArray_whenConvertingUsingAutoboxingAndArraysSetAll_thenGiveExpectedResult() {
    Byte[] newByteArray = new Byte[PRIMITIVE_BYTE_ARRAY.length];
    Arrays.setAll(newByteArray, n -> PRIMITIVE_BYTE_ARRAY[n]);
    Assertions.assertThat(newByteArray)
      .containsExactly(EXPECTED_ARRAY_VALUES);
}

As expected, we successfully converted values using even less code than previously.

6. ArrayUtils from Apache Commons Lang Library

ArrayUtils from the Apache Commons Lang library is a utility class that provides a variety of methods for working with arrays. We can use ArrayUtils.toObject(bytes[] bytes) to create an array of Byte objects from primitives, and conversely, we can create a byte array by calling ArrayUtils.toPrimitive(Byte[] byteObjects).

6.1. ArrayUtils.toObject()

Let’s convert our primitive bytes array into Byte[] using ArrayUtils.toObject():

@Test
void givenPrimitiveByteArray_whenConvertingUsingArrayUtils_thenGiveExpectedResult() {
    Byte[] newByteArray = ArrayUtils.toObject(PRIMITIVE_BYTE_ARRAY);
    Assertions.assertThat(newByteArray)
      .containsExactly(EXPECTED_ARRAY_VALUES);
}

We successfully covered items in just one line of code.

6.2. ArrayUtils.toPrimitive()

Now let’s perform the opposite operation using ArrayUtils.toPrimitive():

@Test
void givenByteArray_whenConvertingArrayUtils_thenGiveExpectedResult() {
    byte[] newByteArray = ArrayUtils.toPrimitive(BYTE_ARRAY);
    Assertions.assertThat(newByteArray)
      .containsExactly(EXPECTED_ARRAY_VALUES);
}

We created a primitive bytes array from Byte[].

7. Conclusion

In this article, we investigated multiple ways to convert a Byte to a byte array and vice versa. Which one to choose depends on the particular case. For the projects that already have Apache Commons in their dependencies, it probably makes sense to use ArrayUtils since it’s the shortest way to achieve the same result.

As usual, the full source code can be found over on GitHub.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>