Conversion Between String and Byte Array

JavaJavaBeginner
Practice Now

Introduction

There are many instances in which we might need to convert a string to a byte array or a byte array to a string. This can be done through the use of character sets. In this lab, we will learn how to do both types of conversions using several different methods.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/FileandIOManagementGroup -.-> java/nio("`NIO`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") subgraph Lab Skills java/oop -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/packages_api -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/nio -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/identifier -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/arrays -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/data_types -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/operators -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/strings -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/variables -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/object_methods -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} java/string_methods -.-> lab-117395{{"`Conversion Between String and Byte Array`"}} end

Using getBytes() method

The getBytes() method of the String class provides a convenient way to obtain a byte array. The String class contains three overloaded versions for the getBytes() method.

String s = "demo!";
byte[] byteArr = s.getBytes();

Using getBytes(String charsetName) method

import java.io.UnsupportedEncodingException;

String s = "demo!";
String namedCharset = "UTF-16";
byte[] byteArr = s.getBytes(namedCharset);

Using getBytes(Charset charset) method

import java.nio.charset.Charset;
import java.util.Arrays;

String s = "demo!";
Charset charset = Charset.forName("UTF-16");
byte[] byteArr = s.getBytes(charset);

Using Charset.encode() method

import java.nio.charset.StandardCharsets;

String s = "demo????????????";
Charset charset = StandardCharsets.ISO_8859_1;
byte[] byteArr = charset.encode(s).array();

Using CharsetEncoder

import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

String s = "demo????????????";
CharsetEncoder charsetEncoder = StandardCharsets.ISO_8859_1.newEncoder();
charsetEncoder.onMalformedInput(CodingErrorAction.IGNORE);
charsetEncoder.onUnmappableCharacter(CodingErrorAction.REPLACE)
             .replaceWith(new byte[] {-121});
byte[] byteArr = charsetEncoder.encode(CharBuffer.wrap(s)).array();

Using String Constructor

byte[] byteArr = {-2, -1, 0, 100, 0, 101, 0, 109, 0, 111, 0, 33};
String stringFromBytes = new String(byteArr, "UTF-16");

Using Charset Instance

Charset charset = Charset.forName("UTF-16");
byte[] byteArr = {-2, -1, 0, 100, 0, 101, 0, 109, 0, 111, 0, 33};
String stringFromBytes = new String(byteArr, charset);

Using Charset.decode() Method

import java.nio.ByteBuffer;

Charset charset = StandardCharsets.UTF_16;
byte[] byteArr = {-2, -1, 0, 100, 0, 101, 0, 109, 0, 111, 0, 33, -10};
String stringFromBytes = charset.decode(ByteBuffer.wrap(byteArr)).toString();

Using CharsetDecoder

import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

CharsetDecoder charsetDecoder = StandardCharsets.UTF_16.newDecoder();
charsetDecoder.onUnmappableCharacter(CodingErrorAction.REPLACE)
              .onMalformedInput(CodingErrorAction.REPLACE)
              .replaceWith("*");
byte[] byteArr = {-2, -1, 0, 100, 0, 101, 0, 109, 0, 111, 0, 33, -10};
String stringFromBytes = charsetDecoder.decode(ByteBuffer.wrap(byteArr)).toString();

Running the code

Copy the code you want to run into a file such as ~/project/Conversion.java and run the following command in the terminal:

javac Conversion.java && java Conversion

Summary

In conclusion, there are multiple ways to convert a string to a byte array or a byte array to a string. The most convenient way is to use the getBytes() method of the String class to generate a byte array and then use the String class constructor to generate a string from the byte array. Alternatively, we can use Charsets and CharsetEncoders and CharsetDecoders to perform the conversions.

Other Java Tutorials you may like