Introduction
In Java, sometimes there is a need to convert a string to bytes. The string in Java works with Unicode values of each character, and bytes are used to reference those values. In this lab, we will learn how to convert a string to byte in Java.
Declare a string
Declare a string variable that contains some text. In this example, let's use "Hello World!".
String message = "Hello World!";
Convert the string to bytes using the default charset
Convert the string to bytes using the getBytes() method of the String class. The getBytes() method encodes the specified string into a sequence of bytes using the platform's default charset.
byte[] bytes = message.getBytes();
Print the bytes
Print the byte array to the console using the Arrays.toString() method.
System.out.println(Arrays.toString(bytes));
Convert the string to bytes using a specific charset
To convert the string to bytes using a specific charset, first, import the Charset package at the beginning of the file.
import java.nio.charset.Charset;
Now, use the forName() method of the Charset class to specify the charset in the getBytes() method.
byte[] bytes = message.getBytes(Charset.forName("UTF-8"));
Print the bytes
Print the byte array to the console using the Arrays.toString() method.
System.out.println(Arrays.toString(bytes));
Convert bytes back to string
To convert bytes back to string, use the String constructor that takes in a byte array as a parameter.
String str = new String(bytes);
Print the converted string
Print the converted string to the console.
System.out.println(str);
Compile and run the program
Compile and run the program in the terminal using the following command:
javac StringToByte.java && java StringToByte
Summary
In this lab, we learned how to convert a string to byte in Java using the getBytes() method and how to specify a charset. We also learned how to convert bytes back to a string using the String constructor.



