We have to write a java program to convert byte array to string. For this, let us first understand what is byte and byte array in java.
What is a byte?
A byte is a numerical data type in java just like an integer data type. It requires a memory of 1 byte i.e. 8 bits. It can hold values from -128 to +127. Thus, for variables whose values fall in this range and require less memory, the byte data type is used.
Now, let us understand what is a byte array.
What is a byte array?
Just like we have an array of integers, we can have an array of bytes. This array of bytes is known as a byte array.
How to initialize a byte array?
To initialize a byte array, you need to know the no. of elements to be present in the array. The declaration for the same is as given below:
byte[] arr=new byte[10];
We can also obtain the byte array by converting a string into bytes using getBytes() method as shown below:
byte[] arr=”Desired String”.getBytes();
How to convert a byte array into a string?
The process of converting a byte array into a string is called decoding.
A byte array can be converted to string using any of the two methods:-
- Using String Class Constructor -> String s=new String(bytearray);
- Using UTF_8 Encoding -> String s=new String(bytearray, StandardCharSets.UTF_8);
Example:
Input:
Enter a string: Hello
Output:
The byte array is : [B@1f96302
The string obtained using the string class constructor is: Hello
The string obtained using UTF_8 encoding is: Hello
Write an algorithm to convert a byte array to string:
- Take a string input from the user.
- Next, obtain the byte array of string using getBytes() method.
- You can also print the byte array.
- To convert the byte array to string using string class constructor, create a string constructor with the byte array as argument. The desired string is obtained. Simply, print the string.
- Or you can also use character encoding for the same. For this, create a string constructor with two arguments – byte array and character encoding using StandardCharSets.UTF_8. Again simply print the string obtained.
Write a program to convert a byte array to string:
import java.util.Scanner; import java.nio.charset.StandardCharsets; public class ByteToString { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter a string"); String s=sc.next(); byte[] arr=s.getBytes(); System.out.println("The byte array is: "+arr); String s1=new String(arr); System.out.println("The string obtained using string class constructor is: "+s1); String s2=new String(arr, StandardCharsets.UTF_8); System.out.println("The string obtained using UTF_8 : "+s2); } }
The output of program to convert a byte array to string: