String To Byte Array - Convert String To Byte Array using getBytes()

String To Byte Array: As seen in String To Char Array post i have previously written, now the same thing, i.e. a string can be converted to byte array easily using the getBytes(). This method returns bytes (byte array) which contains characters in the form of values (ascii values) of the chars in the String object on which it is called. Let us look at the tutorial how we can convert String To Byte Array.


class StringToByteArray
{
public static void main(String args[])
{
// Create string object

String st1="This is first string";

// Convert string to bytes

byte[] b1=st1.getBytes();
// Print bytes in char form

for(int i=0;i<b1.length;i++)
System.out.print((char)b1[i]);
} }
st1.getBytes(): This method returns the byte array of the String st1. This contains ascii values of the characters in the string.

-------------------------------
Output
-------------------------------
This is first string