The String.getBytes() method encodes a string into a sequence of binary bytes, storing the result in a new byte[] array.
Charset Encoding & Binary Serialization: To prevent platform-dependent bugs, production systems should always pass StandardCharsets.UTF_8. To convert characters into a 16-bit char array instead, explore toCharArray() or copy slice buffers with getChars(). For measuring code unit length, see length(), or inspect individual code points with codePointAt().
Java defines three main overloads in java.lang.String to support character set encoding:
// 3 Primary signatures of getBytes() in java.lang.String
public byte[] getBytes()
public byte[] getBytes(Charset charset)
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
| Signature | Encoding Source | Description & Operational Rule |
|---|---|---|
getBytes() |
Charset.defaultCharset() |
Uses the host system's default charset. Unsafe across mixed OS deployments. |
getBytes(Charset charset) |
java.nio.charset.Charset |
Recommended: Type-safe and guarantees identical encoding everywhere. |
getBytes(String charsetName) |
Named String (e.g. "UTF-8") |
Throws checked UnsupportedEncodingException if the charset name is invalid. |
Converting basic ASCII strings into signed 8-bit integers (values -128 to 127) using a for loop:
String my_str = "abcd";
byte[] my_array = my_str.getBytes();
for (int i = 0; i < my_array.length; i++) {
System.out.println("Byte " + i + ": " + my_array[i]);
}Terminal Output:
Byte 0: 97
Byte 1: 98
Byte 2: 99
Byte 3: 100
Calling getBytes() without an argument causes your software to inherit the operating system's default charset. Always pass StandardCharsets.UTF_8 for portable serialization:
import java.nio.charset.StandardCharsets;
String sample = "Java ☕";
// Always specify StandardCharsets.UTF_8 to ensure deterministic byte encoding
byte[] utf8Bytes = sample.getBytes(StandardCharsets.UTF_8);
System.out.println("UTF-8 byte count: " + utf8Bytes.length); // 8 bytes (☕ takes 3 bytes)
// Reconstruct string from bytes using the exact same charset
String restored = new String(utf8Bytes, StandardCharsets.UTF_8);
System.out.println("Restored string: " + restored);Terminal Output:
UTF-8 byte count: 8
Restored string: Java ☕
Different character encodings produce vastly different byte array lengths for the same string:
import java.nio.charset.StandardCharsets;
String text = "Café";
// 1. UTF-8 encoding (é takes 2 bytes: 0xC3 0xA9)
byte[] utf8 = text.getBytes(StandardCharsets.UTF_8);
System.out.println("UTF-8 bytes: " + utf8.length); // 5 bytes
// 2. ISO-8859-1 (Latin-1) encoding (é takes 1 byte: 0xE9)
byte[] latin1 = text.getBytes(StandardCharsets.ISO_8859_1);
System.out.println("ISO-8859-1 bytes: " + latin1.length); // 4 bytes
// 3. UTF-16 encoding (each char takes 2 bytes + 2-byte BOM header)
byte[] utf16 = text.getBytes(StandardCharsets.UTF_16);
System.out.println("UTF-16 bytes: " + utf16.length); // 10 bytesTerminal Output:
UTF-8 bytes: 5
ISO-8859-1 bytes: 4
UTF-16 bytes: 10
While standard ASCII characters encode to 1 byte, emojis (such as 🚀) expand to 4 bytes under UTF-8:
import java.nio.charset.StandardCharsets;
String rocket = "🚀";
// The Rocket emoji requires 4 bytes in UTF-8
byte[] bytes = rocket.getBytes(StandardCharsets.UTF_8);
System.out.println("Rocket UTF-8 length: " + bytes.length); // 4 bytes
System.out.print("Hex byte dump: ");
for (byte b : bytes) {
System.out.printf("%02X ", b);
}
System.out.println();Terminal Output:
Rocket UTF-8 length: 4
Hex byte dump: F0 9F 9A 80
Understanding the fundamental distinction between byte arrays and character arrays:
| Method | Array Element Type | Element Bit-Width | Primary Use Case |
|---|---|---|---|
str.getBytes() |
byte[] (binary) |
8 bits (-128 to 127) | Network transmission, disk storage, cryptography. |
str.toCharArray() |
char[] (text) |
16 bits (0 to 65,535) | In-memory character manipulation and parsing. |
Generating cryptographic hash values from string inputs using binary byte arrays:
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
public class Sha256Hasher {
public static String hash(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// Convert string to bytes safely using UTF-8
byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
}
public static void main(String[] args) throws Exception {
System.out.println("Hash: " + hash("plus2net"));
}
}Terminal Output:
Hash: e3165b63486abdfefba53b0e271eb56a81e3a6c9d72a720ff14a27545920d32f
Formatting network transmission packets with length-prefixed binary payloads:
import java.nio.charset.StandardCharsets;
public class PacketFormatter {
public static byte[] createPayload(String message) {
if (message == null) return new byte[0];
// Prepend 1-byte length header followed by UTF-8 bytes
byte[] textBytes = message.getBytes(StandardCharsets.UTF_8);
byte[] packet = new byte[textBytes.length + 1];
packet[0] = (byte) textBytes.length;
System.arraycopy(textBytes, 0, packet, 1, textBytes.length);
return packet;
}
public static void main(String[] args) {
byte[] packet = createPayload("PING");
System.out.println("Total packet length: " + packet.length); // 5 bytes (1 header + 4 payload)
}
}Terminal Output:
Total packet length: 5
Never assume str.getBytes().length == str.length(). In UTF-8, non-ASCII characters and emojis take 2, 3, or 4 bytes per character. For measuring character counts, use length().
Using string literals like str.getBytes("utf8") risks spelling errors that throw UnsupportedEncodingException. Always prefer type-safe constants like StandardCharsets.UTF_8.
You can compile and run this complete verification class locally in any Java IDE or environment:
import java.nio.charset.StandardCharsets;
public class StringGetBytesFullDemo {
public static void main(String[] args) {
String test = "Hello";
// 1. Verify ASCII byte length equals character length
byte[] b = test.getBytes(StandardCharsets.UTF_8);
if (b.length == 5 && b[0] == 72) {
System.out.println("Check 1 Passed: ASCII string converted to 5 bytes.");
}
// 2. Verify round-trip string reconstruction
String reconstructed = new String(b, StandardCharsets.UTF_8);
if (reconstructed.equals(test)) {
System.out.println("Check 2 Passed: Byte array accurately reconstructed to String.");
}
// 3. Verify empty string produces empty byte array
if ("".getBytes(StandardCharsets.UTF_8).length == 0) {
System.out.println("Check 3 Passed: Empty string produces 0-length byte array.");
}
System.out.println("All String.getBytes() verification tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: ASCII string converted to 5 bytes.
Check 2 Passed: Byte array accurately reconstructed to String.
Check 3 Passed: Empty string produces 0-length byte array.
All String.getBytes() verification tests passed successfully!
Use new String(bytes, StandardCharsets.UTF_8). Always specify the same charset used during encoding.
Java primitives (except char) are signed two's-complement integers. To view an unsigned byte (0 to 255), mask with b & 0xFF.
Calling "".getBytes() returns a valid byte[] of length 0 without allocating excess memory.
Yes. Calling null.getBytes() throws an immediate NullPointerException. Guard inputs with isEmpty().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.