Saturday 4 January 2020

How to convert byte[] to Byte[] in Java?


Traverse through each element and convert.
public static Byte[] getBoxedArray(byte[] arr) {
 if (arr == null)
  return null;

 Byte[] result = new Byte[arr.length];
 int index = 0;
 for (byte i : arr) {
  result[index] = Byte.valueOf(i);
  index++;
 }
 return result;
}


App.java
package com.sample.app;

import java.io.IOException;

public class App {

 private static void printElements(Byte[] arr) {
  for (int i : arr) {
   System.out.print(i + " ");
  }
  System.out.println();
 }

 public static Byte[] getBoxedArray(byte[] arr) {
  if (arr == null)
   return null;

  Byte[] result = new Byte[arr.length];
  int index = 0;
  for (byte i : arr) {
   result[index] = Byte.valueOf(i);
   index++;
  }
  return result;
 }

 public static void main(String args[]) throws IOException {
  byte[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };

  Byte[] result1 = getBoxedArray(arr);
  printElements(result1);

 }

}

Output
1 3 5 7 2 4 6 8 10


You may like

No comments:

Post a Comment