PUBLISHED ON: JANUARY 27, 2021
How to Convert String to Byte in Java
In this post, we are going to convert a string into bytes using Java code. The string is a class in Java that represents the sequence of characters and bytes are used to refer Unicode values of each char in the string.
To convert a string into bytes, we are using the getBytes()
method of String
class that encodes this String into a sequence of bytes based on the specified charset. If the charset is not specified then it uses the platform's default charset.
The Charset is a class in Java that represents the charset and provides methods for creating decoders and encoders which are beneficial in compression and decompression techniques.
The CharSet supports the following standard charset implementations.
Charset
|
Description
|
US-ASCII
|
Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
|
ISO-8859-1
|
ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
|
UTF-8
|
Eight-bit UCS Transformation Format
|
UTF-16BE
|
Sixteen-bit UCS Transformation Format, big-endian byte order
|
UTF-16LE
|
Sixteen-bit UCS Transformation Format, little-endian byte order
|
UTF-16
|
Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
|
Time for an Example:
Let's create an example to get bytes array of a string. Here, we are using getBytes()
method that returns a byte array. Since we did not specify charset here so it will use the default platform's charset.
public class Main {
public static void main(String[] args){
String msg = "StudyTonight.com";
System.out.println(msg);
// string to byte conversion
byte[] bytes = msg.getBytes();
System.out.println(bytes);
}
}
StudyTonight.com
[B@4dc63996
Example: Specify Charset
Let's create another example to get a byte array by specifying the charset to the getBytes()
method. Here, we set UTF-8
as the charset to get byte conversion from string.
import java.nio.charset.Charset;
public class Main {
public static void main(String[] args){
String msg = "StudyTonight.com";
System.out.println(msg);
// string to byte conversion
byte[] bytes = msg.getBytes(Charset.forName("UTF-8"));
System.out.println(bytes);
}
}
StudyTonight.com
[B@4dc63996
Example:
If we want to get a string from the byte array that we created in the above examples then you can use String
class constructor that accepts bytes array as an argument and returns a string as a result.
import java.nio.charset.Charset;
public class Main {
public static void main(String[] args){
String msg = "StudyTonight.com";
System.out.println(msg);
// string to byte conversion
byte[] bytes = msg.getBytes(Charset.forName("UTF-8"));
System.out.println(bytes);
// Byte to String
String str = new String(bytes);
System.out.println(str);
}
}
StudyTonight.com
[B@4dc63996
StudyTonight.com