Convert String to Byte Array in Java Using getBytes(Charset) Method
Last Updated :
22 Nov, 2024
To convert a string to a byte array, we use the getBytes(Charset)
method In Java that transforms the string into a sequence of bytes based on a specified character encoding. This method returns the byte array and relies on the Charset
class to handle character-to-byte mappings.
Example:
Java
// Java program to convert a String to a byte array
// using getBytes(Charset) method with UTF-8 encoding
import java.nio.charset.StandardCharsets;
public class StringToByteArray {
public static void main(String[] args) {
// sample string
String s = "hello";
// Convert string to byte array using UTF-8 encoding
byte[] b = s.getBytes(StandardCharsets.UTF_8);
// Print the byte array
for (byte b1 : b) {
System.out.print(b1 + " ");
}
}
}
Output104 101 108 108 111
Explanation: The above program converts the string "hello" into a byte array using UTF-8 encoding by using the getBytes(StandardCharsets.UTF_8)
method. Then it prints each byte of the resulting byte array.
Syntax of getBytes(Charset) Method
byte[] byteArray = string.getBytes(Charset charset);
Parameter: charset is the character set used to encode the string. For example, StandardCharsets.UTF_8
or Charset.forName("UTF-8")
.
Return type: This function returns the resulting byte array.
Important Points:
- This method always replaces malformed input and unmappable character sequence with its charset's default replacement byte array.
- If the given charset is not a valid charset, then this method will throw UnsupportedEncodingException.
- The length of the byte array is not the same as the given string, it depends upon the character encoding.
Other Ways to Convert a String to Byte Array Using getBytes(Charset)
1. Convert String to Byte Array Using UTF-16 Charset
Example:
Java
// Java Program to illustrate how to
// convert a string to byte array
// Using getBytes(Charset charset)
import java.io.*;
class GFG {
public static void main (String[] args) {
String s = "Hello GeeksforGeeks";
// Display the string before conversion
System.out.println("String: " + s);
try {
// Converting string to byte array
// Using getBytes(Charset charset) method
// Here, we convert the string into UTF-16 values
byte[] r = s.getBytes("UTF-16");
// Displaying the converted string after
// conversion into UTF-16
System.out.println("Result: ");
for (int i = 0; i < r.length; i++) {
System.out.print(r[i] + " ");
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
OutputString: Hello GeeksforGeeks
Result:
-2 -1 0 72 0 101 0 108 0 108 0 111 0 32 0 71 0 101 0 101 0 107 0 115 0 102 0 111 0 114 0 71 0 101 0 101 0 107 0 115
Explanation: The above example converts the string "Hello GeeksforGeeks"
into a byte array using the UTF-16 charset with the getBytes("UTF-16")
method. Then it prints each byte of the resulting byte array to the console.
2. Convert String to Byte Array Using US-ASCII Charset
Example:
Java
// Java Program to illustrate how to
// convert a string to byte array
// Using getBytes(Charset charset)
import java.io.*;
import java.util.Arrays;
class GFG{
public static void main (String[] args)
{
String s1 = "Hello GFG";
// Display the string before conversion
System.out.println("String: " + s1);
try
{
// Converting string to byte array
// Using getBytes(Charset charset) method
// Here, we converts into US-ASCII values
byte[] r = s1.getBytes("US-ASCII");
// Displaying converted string after conversion
// into US-ASCII
System.out.println("Byte Array: " + Arrays.toString(r));
}
catch (UnsupportedEncodingException g)
{
System.out.println("Unsupported character set" + g);
}
}
}
OutputString: Hello GFG
Byte Array: [72, 101, 108, 108, 111, 32, 71, 70, 71]
Explanation: The above example converts the string "Hello GFG"
into a byte array using the US-ASCII charset with the getBytes("US-ASCII")
method. Then it prints the resulting byte array using Arrays.toString()
to display the ASCII values of the characters.
Similar Reads
Convert String to Byte Array in Java Using getBytes(encoding) Method In Java, any sequence of characters within double quotes is treated as String literal. String class represents the character string literal. The string class is present in java.lang package. All string literals in java are immutable i.e their value cannot be changed once created. In Java, the string
3 min read
Java Program to Convert String to Byte Array Using getBytes() Method 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 an
2 min read
Convert a String to Character Array in Java Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.E
2 min read
Java Program to Convert Byte Array to Hex String Byte Array - A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0. Hex String - A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: "245FC" is a hexadec
5 min read
Java Program to Convert Hex String to Byte Array Hex String - A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0's and 1's. Eg: "245FC" is a hexadecimal string. Byte Array - A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte
4 min read
Convert a String to a ByteBuffer in Java In Java, ByteBuffer can be used to perform operations at the Byte level one more thing is this class provides different types of methods for reading writing, and manipulating bytes in a structured way only. In this article, we will learn about String to ByteBuffer in Java. Java Program to Convert St
4 min read