Saturday, August 24, 2024

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.

There are two other variants of getBytes() method in order to provide an encoding for String.

  • getBytes(Charset charset)
  • getBytes(String charsetName)
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));
 }
}

Output

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 onward 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);
 }
}

Output

String - Example String

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!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to int in Java
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Add Double Quotes to a String Java Program

You may also like-

  1. Find Duplicate Elements in an Array Java Program
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Association, Aggregation and Composition in Java
  4. Difference Between Abstract Class And Interface in Java
  5. Multi-Catch Statement in Java Exception Handling
  6. How ArrayList Works Internally in Java
  7. Difference Between ReentrantLock and Synchronized in Java
  8. Java ThreadLocal Class With Examples

No comments:

Post a Comment