STRING INSTANCE METHODS

Java String getBytes() method

getBytes() converts String text into a byte[] array using a chosen character encoding. Use it to write text to files, send it over a network, store it as bytes or pass it to APIs that work with bytes rather than characters.

Converting text to a byte array

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

String tekstas = "Java";
byte[] baitai = tekstas.getBytes(StandardCharsets.UTF_8);

System.out.println(Arrays.toString(baitai));
Console output

[74, 97, 118, 97]

  1. tekstas stores the value Java.
  2. getBytes(StandardCharsets.UTF_8) encodes the text as UTF-8.
  3. The method returns a new byte[] array.
  4. Arrays.toString() simply makes the byte values clear in console output.
  5. The letter's J, a, v, a corresponds in UTF-8 to the bytes 74, 97, 118, 97.

Why is getBytes() an instance method?

getBytes() is called on a specific string because that String object is converted to bytes:

byte[] baitai = tekstas.getBytes(StandardCharsets.UTF_8);

On the left, tekstas is the character sequence; the argument specifies how to encode those characters as bytes.

Method syntax

public byte[] getBytes()

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

public byte[] getBytes(Charset charset)

getBytes() variants
VariantPurpose
getBytes()Uses the environment's default encoding.
getBytes(String charsetName)Uses an encoding name, such as "UTF-8"; may throw UnsupportedEncodingException.
getBytes(Charset charset)Uses the supplied Charset object, such as StandardCharsets.UTF_8.
Return typebyte[]
Important practiceIt is usually better to specify the encoding explicitly rather than rely on the default.

getBytes() without an argument uses the default encoding

import java.nio.charset.Charset;
import java.util.Arrays;

String tekstas = "Java";

System.out.println(Charset.defaultCharset());
System.out.println(Arrays.toString(tekstas.getBytes()));
Possible console output

UTF-8
[74, 97, 118, 97]

getBytes() without an argument uses the environment's default encoding. Modern Java versions often use UTF-8, but explicit encoding is good practice when learning and writing reliable code.

Why does this matter?

If one program encodes text one way and another reads it differently, Lithuanian letters and other non-ASCII characters can become corrupted.

UTF-8 and Lithuanian letters

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

String tekstas = "Ąžuolas";
byte[] baitai = tekstas.getBytes(StandardCharsets.UTF_8);

System.out.println(Arrays.toString(baitai));
System.out.println(tekstas.length());
System.out.println(baitai.length);
Console output

[-60, -124, -59, -66, 117, 111, 108, 97, 115]
7
9

tekstas.length() returns 7because the text Ąžuolas has seven characters. baitai.length returns 9because basic Latin letters usually occupy one byte in UTF-8, while letters such as Ą and ž use two bytes each.

Why do negative numbers appear?

Java byte type ranges from -128 to 127. A byte whose unsigned value exceeds 127can appear as a negative number in a Java array.

ASCII characters have simple byte values

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

String tekstas = "ABC";

System.out.println(Arrays.toString(tekstas.getBytes(StandardCharsets.US_ASCII)));
Console output

[65, 66, 67]

The text ABC belong to ASCII. UTF-8 and US-ASCII therefore produce the same byte values for them: 65, 66 and 67.

Bytes can be converted back to text

import java.nio.charset.StandardCharsets;

String tekstas = "Labas, Java";
byte[] baitai = tekstas.getBytes(StandardCharsets.UTF_8);
String atkurtas = new String(baitai, StandardCharsets.UTF_8);

System.out.println(atkurtas);
Console output

Labas, Java

If text is encoded with StandardCharsets.UTF_8, decode it with the same encoding. The byte sequence then becomes the same String text again.

A different encoding can corrupt text

import java.nio.charset.StandardCharsets;

String tekstas = "ą";
byte[] baitai = tekstas.getBytes(StandardCharsets.UTF_8);
String blogaiAtkurta = new String(baitai, StandardCharsets.ISO_8859_1);

System.out.println(blogaiAtkurta);
Console output

ą

In this example, the text ą is encoded as UTF-8 but decoded as ISO-8859-1. The original letter is lost because the program interprets the same bytes by different rules.

You can specify the encoding by name

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

String tekstas = "Java";

try {
  byte[] baitai = tekstas.getBytes("UTF-8");
  System.out.println(Arrays.toString(baitai));
} catch (UnsupportedEncodingException e) {
  System.out.println("Tokia koduotė nepalaikoma");
}
Console output

[74, 97, 118, 97]

getBytes("UTF-8") works, but this variant uses a textual encoding name and requires handling UnsupportedEncodingException. Where possible, it is more convenient to use StandardCharsets.UTF_8, a ready-made, reliable constant.

A null encoding causes an error

import java.nio.charset.Charset;

String tekstas = "Java";
Charset koduote = null;

System.out.println(tekstas.getBytes(koduote));
Result

NullPointerException

If getBytes(Charset) receives null, Java has no encoding to convert the text to bytes. It throws NullPointerException.

Character length and byte length are different

import java.nio.charset.StandardCharsets;

String ascii = "Java";
String lietuviskai = "ą";

System.out.println(ascii.length());
System.out.println(ascii.getBytes(StandardCharsets.UTF_8).length);
System.out.println(lietuviskai.length());
System.out.println(lietuviskai.getBytes(StandardCharsets.UTF_8).length);
Console output

4
4
1
2

length() measures character units, while getBytes(...).length measures the bytes needed for a particular encoding. They often match for basic ASCII text but can differ for Lithuanian letters.

Writing text to a file

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

String tekstas = "Rezultatas: sėkmingai";
byte[] baitai = tekstas.getBytes(StandardCharsets.UTF_8);

Files.write(Path.of("rezultatas.txt"), baitai);

Files.write() accepts a byte array, so getBytes(StandardCharsets.UTF_8) is a simple way to prepare text for writing. Real projects can also use higher-level methods, such as Files.writeString(), but getBytes() helps explain what happens at a lower level.

The old getBytes(...) variant is deprecated

The Java API still has the old method getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin), marked deprecated. Do not use it in new code because it does not correctly convert characters to bytes. Focus on the variants accepting a Charset, an encoding name or no argument.

Common mistakes

  • Using getBytes() without an encoding when results must be consistent across environments.
  • Encoding text one way and decoding it another way.
  • Forgetting that byte[] is a byte array, not text.
  • Assuming that length() and getBytes(...).length always return the same number.
  • Using getBytes(String charsetName) where it is simpler to use StandardCharsets.UTF_8.
  • Confusing character encoding with encryption: getBytes() does not encrypt text; it only converts it to bytes.

When should you use getBytes()?

getBytes() Use it when sending text to byte-based destinations: files, network requests, database fields, hash functions, digital signatures or lower-level APIs. Usually choose getBytes(StandardCharsets.UTF_8)because an explicit encoding prevents cross-system errors.