In this example we will discuss how to print byte array in java . We will write a java program to print byte array . We will byte array using iteration in this example . In Second example we will convert byte by byte to int array then print decimal value of byte array . Let’s see these example one by one.
Print byte array In Java
We will initialize byte array in this example . Then we will iterateĀ this byte array and print value of element of byte array using System.out.print() method . See java code to print byte array in java .
public class PrintByteArray {
public static void main(String[] args) {
//initialize byte array
byte[] a = { 1,2,3};
//iterate byte array
for(int i=0; i< a.length ; i++) {
System.out.print(a[i] +" ");
}
}
}
Output:
1 2 3
Convert bytes to decimal In java
In this example we will write a java program to print byte array as decimal in java . We will initialize byte array then we convert byte by byte to decimal and make a int array . After that we print element by element of this int array in this example .Let’s see java program for this .
public class PrintByteArrayAsChar {
public static void main(String[] args) {
//initialize byte array
byte[] bytes1 = new byte[] { -1, -128, 1, 127 };
int[] bytesArray = bytearray2intarray(bytes1);
for (int i : bytesArray) {
System.out.print(" "+ i);
}
}
public static int[] bytearray2intarray(byte[] barray)
{
int[] iarray = new int[barray.length];
int i = 0;
for (byte b : barray)
iarray[i++] = b & 0xff;
return iarray;
}
}
In this tutorial we how to print byte array in java. We converted byte to decimal then print int array .You can see more java program for practice .