How to convert Byte Array to String in java

Sometimes, we may need to convert String to bytes Array but how to convert bytes array to String back.

toString method does not work correctly here as it just print bytes in String format.

You can use String's constructor to get String back.

Example:

package org.arpit.java2blog;

public class StringContentEqualsExample {
 public static void main(String[] args) {
  String str1 = "java2blog";
  byte[] bytes=str1.getBytes();
 
  System.out.println(bytes.toString());
  
  String origStr1=new String(bytes);
  System.out.println(origStr1);
  
 }
}

When you run above program, you will get below output:
[B@e1641c0
java2blog

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012