Java String getBytes()

This function takes no arguments and used the default charset to encode the string into bytes. getbytes() function in Java is used to convert a string into a sequence of bytes and returns an array of bytes. 

Syntax

public byte[] getBytes()

Example 1:

Java




// Java Program to Demonstrate
// Working of getByte() Method
 
// Importing required classes
import java.util.*;
 
// Main class
// GetByte
public class GFG {
    // Main driver method
    public static void main(String args[])
    {
        // Declaring and initializing a string
        String gfg = "Geeks for Geeks";
 
        // Displaying string values before conversion
        System.out.println(
            "The String before conversion is : ");
        System.out.println(gfg);
 
        // Converting the string into byte
        // using getBytes() method
        byte[] b = gfg.getBytes();
 
        // Display message only
        System.out.println(
            "The String after conversion is : ");
 
        // Printing converted string after conversion
        for (int i = 0; i < b.length; i++) {
            System.out.print(b[i]);
        }
    }
}


Output

The String before conversion is : 
Geeks for Geeks
The String after conversion is : 
71101101107115321021111143271101101107115

String.getByte() Method in Java

In Java, getBytes() encodes a string into a sequence of bytes using the named character set and storing the result into a new byte array. This function can be implemented in two ways. Both ways are discussed below as follows:

  • getBytes()
  • getBytes(Charset charset)

Let us discuss and implement the first use case which is as follows:

Similar Reads

Java String getBytes()

This function takes no arguments and used the default charset to encode the string into bytes. getbytes() function in Java is used to convert a string into a sequence of bytes and returns an array of bytes....

Java String getBytes(Charset charset)

...

Contact Us