Java Byte Array to String

By Arvind Rai, December 15, 2022
On this page, we will learn to convert byte[] to String in our Java application. We can convert byte[] to String using String constructors. The String provides constructors for this purpose using bytes, offset, length and charset parameters.

1. Using bytes

Find the String constructor from Java doc.
public String(byte[] bytes) 
It constructs a new String by decoding the specified bytes array using default charset of the platform.
Example :
byte[] bytes =  "Hello World!".getBytes();
String s = new String(bytes);
System.out.println(s); 
Output
Hello World! 

2. Using bytes, offset and length

Find the String constructor using bytes, offset and length.
public String(byte[] bytes, int offset, int length) 
Constructs new String using following parameters.
bytes : The bytes to be decoded into characters.
offset : The index of the first byte to decode.
length : The number of bytes to decode.

Example :
byte[] bytes =  "My name is Neo.".getBytes();
String s = new String(bytes, 3, 12);
System.out.println(s); 
Output
name is Neo. 

3. Using bytes, offset, length and charsetName

Find the String constructor using bytes, offset, length and charsetName.
public String(byte[] bytes, int offset, int length, String charsetName) 
Constructs new String.
charsetName : The name of a supported charset.
Throws
The method can throw UnsupportedEncodingException and IndexOutOfBoundsException.

Example :
We can use standard charsets such as US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE and UTF-16 .
Example :
String s = new String(bytes, 3, 12, "US-ASCII"); 

4. Using bytes, offset, length and charset

Find the String constructor using bytes, offset, length and charset.
public String(byte[] bytes, int offset, int length, Charset charset) 
Constructs new String.
charset : The Charset to be used to decode the byte.
Example
String s = new String(bytes, 3, 12, StandardCharsets.US_ASCII); 

5. Using bytes and charsetName

Find the String constructor using bytes and charsetName.
String(byte[] bytes, String charsetName) 
Constructs new String.
Example :
String s = new String(bytes, "UTF-8"); 

6. Using bytes and charset

Find the String constructor using bytes and charset.
String(byte[] bytes, Charset charset) 
Constructs new String.
Example :
String s = new String(bytes, StandardCharsets.UTF_8); 

Reference

Class String
POSTED BY
ARVIND RAI
ARVIND RAI











©2023 concretepage.com | Privacy Policy | Contact Us