Java String getBytes() method
getBytes() method returns sequence of bytes.
Syntax:
There are three variants of getBytes() method: public byte[] getBytes() public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset)
Returns:
It returns sequence of bytes.
Java String getBytes() Example 1
public class JavaStringGetBytesEx1
{
public static void main(String args[])
{
String s1="ghijklm";
byte[] barr=s1.getBytes();
for(int i=0;i<barr.length;i++){
System.out.println(barr[i]);
}
}
}
Output:
103 104 105 106 107 108 109
Java String getBytes() Example 2
public class JavaStringGetBytesEx2
{
public static void main(String[] args)
{
String str = "tutorialandexample";
// Copy the contents of the String to a byte array.
byte[] byte_arr = str.getBytes();
// Create a new String using the contents of the byte array.
String new_str = new String(byte_arr);
String str1 = new_str.concat(".com");
// Display the contents of the byte array.
System.out.println("\nBest online Tutorial site : " +
str1 + "\n");
}
}
Output:
Best online Tutorial site : tutorialandexample.com
Java String getBytes() Example 3
import java.nio.charset.Charset;
public class JavaStringGetBytesEx3 {
public static void main(String[] args) {
try {
String str = "tutorialandexample.com";
System.out.println();
System.out.println("\n Given String = " + str);
// copy the contents of the String to a byte array
byte[] arr = str.getBytes(Charset.forName("ASCII"));
String s1 = new String(arr);
System.out.println(" New string = " + s1);
System.out.println();
} catch (Exception e) {
System.out.print(e.toString());
System.out.println();
}
}
}
Output:
Given String = tutorialandexample.com New string = tutorialandexample.com
Java String getBytes() Example 4
import java.nio.charset.Charset;
public class JavaStringGetBytesEx4 {
public static void main(String[] args) {
try {
String str = "tutorialandexample.com";
System.out.println();
System.out.println("\n Given String = " + str);
// copy the contents of the String to a byte array
byte[] arr = str.getBytes(Charset.forName("ASCII"));
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
String s1 = new String(arr);
System.out.println(" New string = " + s1);
System.out.println();
} catch (Exception e) {
System.out.print(e.toString());
System.out.println();
}
}
}
Output:
Given String = tutorialandexample.com 116 117 116 111 114 105 97 108 97 110 100 101 120 97 109 112 108 101 46 99 111 109 New string = tutorialandexample.com
