How to convert String to Byte array in java

Sometimes, we need to convert String to byte array. We can use getBytes() method of String to do it,

Method syntax:

public byte[] getBytes()

String getBytes Example:

package org.arpit.java2blog;

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

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

There is one more overloaded method for getBytes 

Method syntax:
public byte[] getBytes(String charSetName)

It encodes String to specified charset format. You can read about charset from http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html

Lets encode above String in charSet UTF-16LE and UTF-16BE
package org.arpit.java2blog;

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

public class StringBytesExample {
 public static void main(String[] args) {
  String str1 = "java2blog";
  byte[] bytesDef=str1.getBytes();
  byte[] bytesUTFLE = null;
  byte[]  bytesUTFBE = null;
  try {
   bytesUTFLE = str1.getBytes("UTF-16LE");
   bytesUTFBE=str1.getBytes("UTF-16BE");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
  
  System.out.println("Encoding using default charSet");
  for (int i = 0; i < bytesDef.length; i++) {
   System.out.print(bytesDef[i]);
  }
  System.out.println("\n----------------------------------");
  System.out.println("\nEncoding using UTF-16LE charset");
  for (int i = 0; i < bytesUTFLE.length; i++) {
   System.out.print(bytesUTFLE[i]);
  }
  System.out.println("\n----------------------------------");
  System.out.println("\nEncoding using UTF-16BE charset");
  for (int i = 0; i < bytesUTFBE.length; i++) {
   System.out.print(bytesUTFBE[i]);
  } 
 }
}
When you run above program, you will get below output:
Encoding using default charSet
10697118975098108111103
----------------------------------

Encoding using UTF-16LE charset
10609701180970500980108011101030
----------------------------------

Encoding using UTF-16BE charset
01060970118097050098010801110103

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