Open In App

Java Program to Convert String to Byte Array Using getBytes() Method

Last Updated : 19 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getByte() method. It is the easiest way to convert a string to a byte array. This method converts the given string to a sequence of bytes using the platform’s default charset and returns an array of bytes. It is a predefined function of string class. But it is an error-prone method and can return an erroneous result if the platform character encoding doesn’t match with the expected encoding.

Syntax:

public byte[] getBytes()

Note:

  • In this method, the platform’s default encoding is used to convert the given string to the byte array if you do not specify any character encoding in the method.
  • The length of the byte array is not the same as the given string, it depends upon the character encoding.

Example 1:

Java




// Java program to illustrate how to
// convert a string to byte array
// Using getBytes()
  
import java.io.*;
  
class GFG {
  
    public static void main(String[] args)
    {
  
        // Initializing String
        String ss = "Hello GeeksforGeeks";
  
        // Display the string before conversion
        System.out.println("String: " + ss);
  
        // Converting string to byte array
        // Using getBytes() method
        byte[] res = ss.getBytes();
  
        System.out.println("Byte Array:");
  
        // Display the string after conversion
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i]);
        }
    }
}


Output

String: Hello GeeksforGeeks
Byte Array:
72101108108111327110110110711510211111471101101107115

Example 2:

Java




// Java program to illustrate how to
// convert a string to byte array
// Using getBytes()
  
import java.io.*;
import java.util.Arrays;
  
class GFG {
  
    public static void main(String[] args)
    {
  
        // Initializing String
        String ss = "GeeksforGeeks";
  
        // Display the string before conversion
        System.out.println("String: " + ss);
  
        // Converting string to byte array
        // Using getBytes() method
        byte[] res = ss.getBytes();
  
        // Display the string after conversion
        System.out.println("Byte Array:"
                           + Arrays.toString(res));
    }
}


Output

String: GeeksforGeeks
Byte Array:[71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads