Table of Contents
Sometimes, we need to convert String to byte array. We can use getBytes() method of String to do it,
When you run above program, you will get below output:
Method syntax:
1 2 3 |
public byte[] getBytes() |
String getBytes Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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()); } } |
1 2 3 4 5 |
9 9 [B@e1641c0 |
There is one more overloaded method for getBytes
Method syntax:
1 2 3 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
Encoding using default charSet 10697118975098108111103 ---------------------------------- Encoding using UTF-16LE charset 10609701180970500980108011101030 ---------------------------------- Encoding using UTF-16BE charset 01060970118097050098010801110103 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.