Convert a string to byte sequence(UTF-8,US-ASCII) in Java

getBytes(), getBytes(Charset charset) and getBytes(String charset) methods of String class can be used to convert a string to byte array of specific character set.

Return type of getBytes(), getBytes(Charset charset) and getBytes(String charset) method is byte array i.e. byte[].


getBytes() method

getBytes() method converts a string to byte array with default charset.

Example

class StringTest{

public static void main(String args[]){

String str="Superb";

byte[] strtobyte=str.getBytes();

System.out.println("String in Bytes");

for(int i=0;i<6;i++){

System.out.println("'developer' is present in the string");

}

}

}

Output

String in Bytes

83

117

112

101

114

98


getBytes(String charset) method

getBytes(String charset) method converts a string to byte array with the specified charset in arguments.

Example

class StringTest{

public static void main(String args[]){

String str="Wonderful";

try{

byte[] strtobyte=str.getBytes("UTF-8");

System.out.println("String in Bytes");

for(int i=0;i<9;i++){

System.out.println(strtobyte[i]);

}

}

catch(Exception e){

System.out.println("Error is "+e);

}

}

}

Output

String in Bytes

87

111

110

100

101

114

102

117

108


getBytes(Charset charset) method

getBytes(String charset) method converts a string to byte array with the specified charset.

Example

import java.nio.charset.Charset;

class StringTest{

public static void main(String args[]){

String str="Nice";

try{

byte[] strtobyte=str.getBytes(Charset.forName("US-ASCII"));

System.out.println("String in Bytes");

for(int i=0;i<4;i++){

System.out.println(strtobyte[i]);

}

}

catch(Exception e){

System.out.println("Error is "+e);

}

}

}

Output

String in Bytes

78

105

99

101