• To convert byte array to string we have a constructor in String class which is taking byte array as an argument.
  • So just we need to pass byte array object to string as argument while creating String class object.

  1.  package com.instanceofjavaforus;
  2.  
  3. public class ByteArrayToString {
  4.    /*
  5.    * This method converts a byte array to a String object.
  6.      */
  7.  
  8.     public static void convertByteArrayToString() {
  9.  
  10.         byte[] byteArray = new byte[] {78,73, 67,69};
  11.         String value = new String(byteArray);
  12.        System.out.println(value);
  13.  
  14.     }
  15.  
  16.     public static void main(String[] args) {
  17.         ByteArrayToString.convertByteArrayToString();
  18.     }
  19.  
  20. }

Output:


  1. NICE

 

Convert String to Byte Array:

  1.  package com.instanceofjava;
  2. public class StringTOByteArray{
  3.    /*
  4.    * This example shows how to convert a String object to byte array.
  5.      */

  6.     public static void main(String[] args) {
  7.       
  8.     String data = "Instance of java";
  9.  
  10.     byte[] byteData = data.getBytes();
  11.  
  12.     System.out.println(byteData);
  13.  
  14.     }
  15.  
  16. }



Output:


  1. [B@3b26456a

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

2 comments for Convert Byte Array to String

  1. thanks for tutor, i can try this in my web
    http://informasipekerjaan.com

    ReplyDelete
  2. System.out.println prints the object reference. To print contents use System.out.write.

    ReplyDelete

Select Menu