Tutorials  /  JavaScript

String to Byte Array and Byte Array to String Conversion in Java

Ccentron Redaktion · January 2024 ·3 min read ·JavaScript, Tutorial

Today we will learn how to convert String to byte array in java. We will also learn how to convert byte array to String in Java.

String to Byte Array

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform’s default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert it in java.

Go
package com.journaldev.util;

        import java.util.Arrays;

        public class StringToByteArray {

            public static void main(String[] args) {
                String str = "PANKAJ";
                byte[] byteArr = str.getBytes();
                // print the byte[] elements
                System.out.println("String to byte array: " + Arrays.toString(byteArr));
            }
        }

We can also get it using the below code.

Code
byte[] byteArr = str.getBytes("UTF-8");

However if we provide Charset name, then we will have to either catch UnsupportedEncodingException exception or throw it. Better approach is to use StandardCharsets class introduced in Java 1.7 as shown below.

Code
byte[] byteArr = str.getBytes(StandardCharsets.UTF_8);

That’s all the different ways to convert String to byte array in java.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Java Byte Array to String

Let’s look at a simple program showing how to convert byte array to String in Java.

Go
package com.journaldev.util;

        public class ByteArrayToString {

            public static void main(String[] args) {
                byte[] byteArray = { 'P', 'A', 'N', 'K', 'A', 'J' };
                byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 };

                String str = new String(byteArray);
                String str1 = new String(byteArray1);

                System.out.println(str);
                System.out.println(str1);
            }
        }

Did you notice that I am providing char while creating the byte array? It works because of autoboxing and char ‘P’ is being converted to 80 in the byte array. That’s why the output is the same for both conversions. String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used.

Code
String str = new String(byteArray, StandardCharsets.UTF_8);

String class also has a method to convert a subset of it.

Code
byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 };
String str = new String(byteArray1, 0, 3, StandardCharsets.UTF_8);

Above code is perfectly fine and ‘str’ value will be ‘PAN’. That’s all about converting in Java.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren