- Convert Byte[] to String and Vice-versa
- String to byte array, byte array to String in Java
- String to byte array
- Java byte array to String
- In Java How to convert Byte[] Array To String and String to Byte[]?
- There are multiple ways you could covert byte[] to String and String to byte[].
- Java Code:
- Eclipse console Output:
- Tech Tutorials
- Sunday, November 14, 2021
- Convert String to Byte Array Java Program
- Converting String to byte[] in Java
- Conversion of string to byte array with encoding
- Converting byte array to String in Java
Convert Byte[] to String and Vice-versa
Learn to convert byte[] array to String and convert String to byte[] array in Java with examples. Conversion between byte array and string may be used in many cases including IO operations, generating secure hashes etc.
Until it is absolute necessary, DO NOT convert between string and byte array. They both represent different data; and are there to serve specific purposes i.e. strings are for text, byte[] is for binary data.
1.1. Using String Constructor
To convert a byte array to String , you can use String class constructor with byte[] as the constructor argument.
byte[] bytes = "hello world".getBytes(); String s = new String(bytes);
Since Java 8, we have Base64 class available. As you might be aware that Base64 is a way to encode binary data, while UTF-8 and UTF-16 are ways to encode Unicode text data. So if you need to encode arbitrary binary data as text, Base64 is the way to go.
byte[] bytes = "hello world".getBytes(); String s = Base64.getEncoder().encodeToString(bytes);
To convert from string to byte array, use String.getBytes() method. Please note that this method uses the platform’s default charset.
String string = "howtodoinjava.com"; byte[] bytes = string.getBytes();
The Base64.getDecoder().decode() method converts a string to a byte array.
String string = "howtodoinjava.com"; byte[] bytes = Base64.getDecoder().decode(string);
We should focus on the input data type when converting between byte[] array and String in Java.
- Use the String class when you input data in string or text content.
- Use Base64 class when you input data in a byte array.
Drop me your questions in the comments section.
String to byte array, byte array to String in Java
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the 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 String to byte array in java.
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)); >>
Below image shows the output when we run the above program. We can also get the byte array using the below 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.
byte[] byteArr = str.getBytes(StandardCharsets.UTF_8);
Java byte array to String
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); > >
Below image shows the output produced by the above program. 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 the byte array to string conversion. String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used to convert byte array to String in Java.
String str = new String(byteArray, StandardCharsets.UTF_8);
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 byte array to String in Java. You can checkout more array examples from our GitHub Repository. Reference: getBytes API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
In Java How to convert Byte[] Array To String and String to Byte[]?
How to convert Byte[] Array to String in Java? How to convert UTF-8 byte[] to string? Convert Java Byte Array to String to Byte Array.
String stores textual data and for storing binary data you would need byte[]. In ideal situation you would avoid using the same in your production ready build. Here is a code, just incase if you need to do conversion in your application from String to byte[] and vice versa.
There are multiple ways you could covert byte[] to String and String to byte[].
We will manipulate String and byte[] 5 different ways .
- Convert String to byte[] Array using getBytes()
- Convert String to byte[] Array using UTF_8 encoding
- Encode and Decode to String using Base64 encoding
- Convert Byte[] to String using new String()
- Convert Byte[] to String using UTF_8 encoding
toString() function on String object wont return actual string but only HashValue. Look for all comments mentioned in below Java program.
Java Code:
package crunchify.com.tutorials; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; /** * @author Crunchify.com * In Java How to convert Byte[] Array To String and String to Byte[]? * Version: 1.2 */ public class CrunchifyByteArrayToString < public static void main(String[] args) throws UnsupportedEncodingException < // Method-1: Convert String to byte[] Array using getBytes() String crunchifyString = "Crunchify Example on Byte[] to String. "; // getBytes() encodes this String into a sequence of bytes using the platform's // default charset, storing the result into a new byte array. byte[] crunchifyByte = crunchifyString.getBytes(); System.out.println("crunchifyString : " + crunchifyString); // toString() Returns a string representation of the contents of the specified array. // The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). // Elements are converted to strings as by String.valueOf(byte). Returns "null" if a is null. System.out.println("crunchifyByte : " + Arrays.toString(crunchifyByte)); // Method-2: Convert String to byte[] Array using UTF_8 encoding String crunchifyString2 = "This is test for converting String to byte. "; byte[] crunchifyByte2 = crunchifyString2.getBytes(StandardCharsets.UTF_8); System.out.println("\ncrunchifyString2 : " + crunchifyString2); System.out.println("crunchifyByte2 : " + Arrays.toString(crunchifyByte2)); // Method-3: Encode and Decode to String using Base64 encoding // encodeToString() Encodes the specified byte array into a String using the Base64 encoding scheme. // This method first encodes all input bytes into a base64 encoded byte array and then constructs // a new String by using the encoded byte array and the ISO-8859-1 charset. String crunchifyEncodedValue = Base64.getEncoder().encodeToString(crunchifyByte2); System.out.println("crunchifyByte2 encoded value : " + crunchifyEncodedValue); // decode() Decodes a Base64 encoded String into a newly-allocated byte array using the Base64 encoding scheme. // An invocation of this method has exactly the same effect as invoking decode(src.getBytes(StandardCharsets.ISO_8859_1)) byte[] crunchifyByte3 = Base64.getDecoder().decode(crunchifyEncodedValue); System.out.println("crunchifyByte2 decoded value : " + Arrays.toString(crunchifyByte3)); // Method-4: Convert Byte[] to String using new String() String crunchifyDecodedData = new String(crunchifyByte3); System.out.println("\nDecrypted String : " + crunchifyDecodedData); // Method-5: Convert Byte[] to String using UTF_8 encoding String decodedDataUsingUTF8; // UTF_8 is Eight-bit UCS Transformation Format. decodedDataUsingUTF8 = new String(crunchifyByte3, StandardCharsets.UTF_8); System.out.println("Text Decrypted using UTF-8 : " + decodedDataUsingUTF8); >>
Eclipse console Output:
Just run above program as Java Application and you should see similar result.
crunchifyString : Crunchify Example on Byte[] to String. crunchifyByte : [67, 114, 117, 110, 99, 104, 105, 102, 121, 32, 69, 120, 97, 109, 112, 108, 101, 32, 111, 110, 32, 66, 121, 116, 101, 91, 93, 32, 116, 111, 32, 83, 116, 114, 105, 110, 103, 46, 46, 46] crunchifyString2 : This is test for converting String to byte. crunchifyByte2 : [84, 104, 105, 115, 32, 105, 115, 32, 116, 101, 115, 116, 32, 102, 111, 114, 32, 99, 111, 110, 118, 101, 114, 116, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 32, 116, 111, 32, 98, 121, 116, 101, 46, 46, 46, 33] crunchifyByte2 encoded value : VGhpcyBpcyB0ZXN0IGZvciBjb252ZXJ0aW5nIFN0cmluZyB0byBieXRlLi4uIQ== crunchifyByte2 decoded value : [84, 104, 105, 115, 32, 105, 115, 32, 116, 101, 115, 116, 32, 102, 111, 114, 32, 99, 111, 110, 118, 101, 114, 116, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 32, 116, 111, 32, 98, 121, 116, 101, 46, 46, 46, 33] Decrypted String : This is test for converting String to byte. Text Decrypted using UTF-8 : This is test for converting String to byte. Process finished with exit code 0
Let me know if you see any issue running above program.
If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.
Tech Tutorials
Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.
Sunday, November 14, 2021
Convert String to Byte Array Java Program
In this post we’ll see a Java program to convert a String to byte array and byte array to String in Java.
Converting String to byte[] in Java
String class has getBytes() method which can be used to convert String to byte array in Java.
getBytes()— Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
import java.util.Arrays; public class StringToByte < public static void main(String[] args) < String str = "Example String"; byte[] b = str.getBytes(); System.out.println("Array " + b); System.out.println("Array as String" + Arrays.toString(b)); >>
Array [B@2a139a55 Array as String[69, 120, 97, 109, 112, 108, 101, 32, 83, 116, 114, 105, 110, 103]
As you can see here printing the byte array gives the memory address so used Arrays.toString in order to print the array values.
Conversion of string to byte array with encoding
Suppose you want to use “UTF-8” encoding then it can be done in 3 ways.
String str = "Example String"; byte[] b; try < b = str.getBytes("UTF-8"); >catch (UnsupportedEncodingException e) < // TODO Auto-generated catch block e.printStackTrace(); >b = str.getBytes(Charset.forName("UTF-8")); b = str.getBytes(StandardCharsets.UTF_8);
Using str.getBytes(«UTF-8») method to convert String to byte array will require to enclose it in a try-catch block as UnsupportedEncodingException is thrown. To avoid that you can use str.getBytes(Charset.forName(«UTF-8»)) method. Java 7 and above you can also use str.getBytes(StandardCharsets.UTF_8);
Converting byte array to String in Java
String class has a constructor which takes byte array as an argument. Using that you can get the String from a byte array.
String(byte[] bytes)— Constructs a new String by decoding the specified array of bytes using the platform’s default charset.
If you want to provide a specific encoding then you can use the following constructor-
String(byte[] bytes, Charset charset)— Constructs a new String by decoding the specified array of bytes using the specified charset.
public class StringToByte < public static void main(String[] args) < String str = "Example String"; // converting to byte array byte[] b = str.getBytes(); // Getting the string from a byte array String s = new String (b); System.out.println("String - " + s); >>
That’s all for this topic Convert String to Byte Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!