The getBytes()
method in Java encodes a string into a sequence of bytes.
The getBytes()
method can be declared as shown in the code snippet below:
public byte[] getBytes()
The getBytes()
method returns an array of bytes that is a string encoded into a sequence of bytes.
Consider the code snippet below, which demonstrates the use of the getBytes()
method.
import java.util.Arrays;public class Main{public static void main(String args[]){String str="ABCDEFG";byte[] arr=str.getBytes();for(int index = 0; index < arr.length; index += 1){System.out.println((char)arr[index]);}}}
We declare the string str
in line 4. The getBytes()
method is used in line 5 to encode str
in a sequence of bytes. In line 6 to 7, we use the for
loop to print each element at every index.