tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Articles > Java > Basics > How to convert String to Byte Array

How to convert String to Byte Array 

The following example shows converting String to Byte array. String class provides the following APIs for encoding String into a sequence of bytes.

java.lang.String
  • public byte[] getBytes()
    Encodes this String to byte array with default Charset.
  • public byte[] getBytes(String charsetName)
    Encodes this String to byte array with given Charset name.
  • public byte[] getBytes(Charset charset)
    Encodes this String to byte array with given Charset.

File Name  :  
com/bethecoder/articles/basics/str2bytea/String2ByteArrayTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.articles.basics.str2bytea;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;

public class String2ByteArrayTest {

  /**
   @param args
   @throws UnsupportedEncodingException 
   */
  public static void main(String[] argsthrows UnsupportedEncodingException {

    //Get the bytes encoded in default charset, Charset.defaultCharset()
    String str = "BE THE CODER";
    byte [] bytes = str.getBytes();
    System.out.println(Arrays.toString(bytes));
    
    //Get the bytes encoded in UTF-16 charset
    byte [] bytes2 = str.getBytes("UTF-16");
    System.out.println(Arrays.toString(bytes2));
    
    //Get the bytes encoded in IBM420 charset
    byte [] bytes3 = str.getBytes(Charset.forName("IBM420"));
    System.out.println(Arrays.toString(bytes3));
  
  }

}
   

It gives the following output,
[66, 69, 32, 84, 72, 69, 32, 67, 79, 68, 69, 82]
[-2, -1, 0, 66, 0, 69, 0, 32, 0, 84, 0, 72, 0, 69, 0, 32, 0, 67, 0, 79, 0, 68, 0, 69, 0, 82]
[-62, -59, 64, -29, -56, -59, 64, -61, -42, -60, -59, -39]



 
  


  
bl  br