A string is a list of characters (i.e. code points). The number of bytes taken to represent the string depends entirely on which encoding you use to turn it into bytes.

That said, you can turn the string into a byte array and then look at its size as follows:

// The input string for this test
final String string = "Hello World";

// Check length, in characters
System.out.println(string.length()); // prints "11"

// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"

final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"

final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"

final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"

final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"

So you see, even a simple "ASCII" string can have different number of bytes in its representation, depending which encoding is used. Use whichever character set you're interested in for your case, as the argument to getBytes(). And don't fall into the trap of assuming that UTF-8 represents every character as a single byte, as that's not true either:

final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms

// Check length, in characters
System.out.println(interesting.length()); // prints "4"

// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"

final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"

final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"

final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")

final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")

(Note that if you don't provide a character set argument, the platform's default character set is used. This might be useful in some contexts, but in general you should avoid depending on defaults, and always use an explicit character set when encoding/decoding is required.)

Answer from Andrzej Doyle on Stack Overflow
Top answer
1 of 10
346

A string is a list of characters (i.e. code points). The number of bytes taken to represent the string depends entirely on which encoding you use to turn it into bytes.

That said, you can turn the string into a byte array and then look at its size as follows:

// The input string for this test
final String string = "Hello World";

// Check length, in characters
System.out.println(string.length()); // prints "11"

// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"

final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"

final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"

final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"

final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"

So you see, even a simple "ASCII" string can have different number of bytes in its representation, depending which encoding is used. Use whichever character set you're interested in for your case, as the argument to getBytes(). And don't fall into the trap of assuming that UTF-8 represents every character as a single byte, as that's not true either:

final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms

// Check length, in characters
System.out.println(interesting.length()); // prints "4"

// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"

final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"

final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"

final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")

final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")

(Note that if you don't provide a character set argument, the platform's default character set is used. This might be useful in some contexts, but in general you should avoid depending on defaults, and always use an explicit character set when encoding/decoding is required.)

2 of 10
70

If you're running with 64-bit references:

sizeof(string) = 
8 + // object header used by the VM
8 + // 64-bit reference to char array (value)
8 + string.length() * 2 + // character array itself (object header + 16-bit chars)
4 + // offset integer
4 + // count integer
4 + // cached hash code

In other words:

sizeof(string) = 36 + string.length() * 2

On a 32-bit VM or a 64-bit VM with compressed OOPs (-XX:+UseCompressedOops), the references are 4 bytes. So the total would be:

sizeof(string) = 32 + string.length() * 2

This does not take into account the references to the string object.

๐ŸŒ
JA-VA Code
java-performance.info โ€บ home โ€บ exploring java string byte size: understanding memory usage
Java String Byte Size: Mastering Memory Efficiency
September 26, 2023 - The memory usage of a string is vital because it determines how much memory your program will allocate to store string data. Inefficient use of memory can lead to performance issues and even application crashes if memory resources are exhausted. Understanding and optimizing the byte size of Java strings is crucial for the following reasons:
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ javaโ€™s string.length() and string.getbytes().length
Javaโ€™s String.length() and String.getBytes().length | Baeldung
July 6, 2024 - String.length() โ€“ When we work with characters and the logical content of the string and want to obtain the total number of characters in the string, such as user input max-length validation or shifting characters in a string ยท String.bytes().length โ€“ When we deal with byte-oriented operations and need to know the size of the string in terms of bytes, such as reading from or writing to files or network streams ยท
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 375746 โ€บ java โ€บ byte-size-string
byte size of a string? (Java in General forum at Coderanch)
January 31, 2005 - As Jeanne and Tony's answers make clear, it depends on what you want to do with the String. In Java, the primitive char type is 2 bytes as they are Unicode values. As String uses a char[] to hold the characters, in memory the characters themselves take 2 * s.length() bytes.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 541074 โ€บ java โ€บ Size-String-Bytes
Size of a String in Bytes (I/O and Streams forum at Coderanch)
June 8, 2011 - I am currently building an xml file using Java and sending it to a web service that I know nothing about. There is a field that is limited to 8000 bytes. I have a 1749 character String in this field. When I use getBytes("UTF-8").length it returns 1770 (Well below the 8000 byte limit).
Top answer
1 of 4
51

String.length()

String.length() is the number of 16-bit UTF-16 code units needed to represent the string. That is, it is the number of char values that are used to represent the string and thus also equal to toCharArray().length. For most characters used in western languages this is typically the same as the number of unicode characters (code points) in the string, but the number of code point will be less than the number of code units if any UTF-16 surrogate pairs are used. Such pairs are needed only to encode characters outside the BMP and are rarely used in most writing (emoji are a common exception).

String.getBytes().length

String.getBytes().length on the other hand is the number of bytes needed to represent your string in the platform's default encoding. For example, if the default encoding was UTF-16 (rare), it would be exactly 2x the value returned by String.length() (since each 16-bit code unit takes 2 bytes to represent). More commonly, your platform encoding will be a multi-byte encoding like UTF-8.

This means the relationship between those two lengths are more complex. For ASCII strings, the two calls will almost always produce the same result (outside of unusual default encodings that don't encode the ASCII subset in 1 byte). Outside of ASCII strings, String.getBytes().length is likely to be longer, as it counts bytes needed to represent the string, while length() counts 2-byte code units.

Which is more suitable?

Usually you'll use String.length() in concert with other string methods that take offsets into the string. E.g., to get the last character, you'd use str.charAt(str.length()-1). You'd only use the getBytes().length if for some reason you were dealing with the array-of-bytes encoding returned by getBytes.

2 of 4
9

The length() method returns the length of the string in characters.

Characters may take more than a single byte. The expression String.getBytes().length returns the length of the string in bytes, using the platform's default character set.

๐ŸŒ
Java Mex
javamex.com โ€บ tutorials โ€บ memory โ€บ string_memory_usage.shtml
Memory usage of Java Strings and string-related objects
as mentioned in our discussion of general memory usage of Java objects, every object has at least 8 bytes of housekeeping data, and arrays 12 bytes, and will be padded to a multiple of 16 bytes (in 32-bit versions of Hotspot); a Java String actually consists of more than one object;
Find elsewhere
๐ŸŒ
Javainuse
javainuse.com โ€บ bytesize
Online Text(String) Size Calculator Tool (In Bytes)
Hex Encoder/Decoder Convert text ... JSON -> Java POJO Generate getters/setters from JSON Text Size (Bytes) Measure string length with/without spaces JSON Size (Bytes) Check JSON payload footprint XML Size (Bytes) Measure XML size quickly UTF-8 Encoder/Decoder Round-trip text and UTF-8 bytes JSON -> NDJSON Convert collections to newline-delimited JSON Cron Generator Craft and copy cron expressions JSON -> YAML Convert JSON documents to YAML YAML -> JSON Transform YAML into JSON YAML ...
๐ŸŒ
PixelsTech
pixelstech.net โ€บ home โ€บ articles โ€บ string.length() vs string.getbytes().length in java
String.length() vs String.getBytes().length in Java | PixelsTech
July 26, 2026 - Developers must be aware of this distinction, especially when performing low-level byte operations such as encryption or network transmission, to prevent unexpected data handling issues. In Java, String.length() is to return the number of characters in the string, while String.getBytes().length is to return the number of bytes to represent the string with the specified encoding.
Top answer
1 of 5
7
final String hello_str = "Hello World";

hello_str.getBytes().length is the "byte size", i.e. the number of bytes
2 of 5
5

You probably use about the following to read the file

FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
   /* process line */
   /* report percentage */
}

You need to specify the encoding already at the beginning. If you don't, you should get UTF-8 on Android. It is the default but that can be changed. I would assume that no device does that though.

To repeat what the other answers already stated: The character count is not always the same as the byte count. Especially the UTF encodings are tricky. There are currently 249,764 assigned Unicode characters and potentially over a million (WP) and UTF uses 1 to 4 byte to be able to encode all of them. UTF-32 is the simplest case since it will always use 4 bytes. UTF-8 does that dynamically and uses 1 to 4 bytes. Simple ASCII characters use just 1 byte. (source: UTF & BOM FAQ)

To get the amount of bytes you can use e.g. line.getBytes("UTF-8").length(). One big disadvantage is that this is very inefficient since it creates copy of the String internal array each time and throws it away after that. That is #1 addressed at Android | Performance Tips

It is also not 100% accurate in terms of actual bytes read from the file for following reasons:

  • UTF-16 textfiles for example often start with a special 2 byte BOM (Byte Order Mark) to signal whether they have to interpreted little or big endian. Those 2 (UTF-8: 3, UTF-32: 4) bytes are not reported when you just look at the String you get from your reader. So you are already some bytes off here.

  • Turning every line of a file into an UTF-16 String will include those BOM bytes for each line. So getBytes will report 2 bytes too much for each line.

  • Line ending characters are not part of the resulting line-String. To make things worse you have different ways of signaling the end of a line. Usually the Unix-Style '\n' which is only 1 character or the Windows-Style '\r''\n' which is two characters. The BufferedReader will simply skip those. Here your calculation is missing a very variable amount of bytes. From 1 byte for Unix/UTF-8 to 8 bytes for Windows/UTF-32.

The last two reasons would negate each other if you have Unix/UTF-16, but that is probably not the typical case. The effect of the error also depends on line length: if you have an error of 4 byte for each line that is in total only 10 bytes long your progress will be quite considerably wrong (if my math is good your progress would be at 140% or 60% when after the last line, depending on whether your calculation assumes -4 or +4 byte per line)

That means so far that regardless of what you do, you get no more than an approximation.

Getting the actual byte-count could probably be done if you write your own special byte counting Reader but that would be quite a lot of work.

An alternative would be to use a custom InputStream that counts how much bytes are actually read from the underlying stream. That's not too hard to do and it does not care for encodings.

The big disadvantage is that it does not increase linearly with the lines you read since BufferedReader will fill it's internal buffer and read lines from there, then read the next chunk from the file and so on. If the buffer is large enough you are at 100% at the first line already. But I assume your files are big enough or you would not want to find out about the progress.

This for example would be such an implementation. It works but I can't guarantee that it is perfect. It won't work if streams use mark() and reset(). File reading should no do that though.

static class CountingInputStream extends FilterInputStream {
    private long bytesRead;

    protected CountingInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        int result = super.read();
        if (result != -1) bytesRead += 1;
        return result;
    }
    @Override
    public int read(byte[] b) throws IOException {
        int result = super.read(b);
        if (result != -1) bytesRead += result;
        return result;
    }
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int result = super.read(b, off, len);
        if (result != -1) bytesRead += result;
        return result;
    }
    @Override
    public long skip(long n) throws IOException {
        long result = super.skip(n);
        if (result != -1) bytesRead += result;
        return result;
    }

    public long getBytesRead() {
        return bytesRead;
    }
}

Using the following code

File file = new File("mytestfile.txt");
int linesRead = 0;
long progress = 0;
long fileLength = file.length();
String line;

CountingInputStream cis = new CountingInputStream(new FileInputStream(file));
BufferedReader br = new BufferedReader(new InputStreamReader(cis, "UTF-8"), 8192);
while ((line = br.readLine()) != null) {
    long newProgress = cis.getBytesRead();
    if (progress != newProgress) {
        progress = newProgress;
        int percent = (int) ((progress * 100) / fileLength);
        System.out.println(String.format("At line: %4d, bytes: %6d = %3d%%", linesRead, progress, percent));
    }
    linesRead++;
}
System.out.println("Total lines: " + linesRead);
System.out.println("Total bytes: " + fileLength);
br.close();

I get output like

At line:    0, bytes:   8192 =   5%
At line:   82, bytes:  16384 =  10%
At line:  178, bytes:  24576 =  15%
....
At line: 1621, bytes: 155648 =  97%
At line: 1687, bytes: 159805 = 100%
Total lines: 1756
Total bytes: 159805

or in case of the same file UTF-16 encoded

At line:    0, bytes:  24576 =   7%
At line:   82, bytes:  40960 =  12%
At line:  178, bytes:  57344 =  17%
.....
At line: 1529, bytes: 303104 =  94%
At line: 1621, bytes: 319488 =  99%
At line: 1687, bytes: 319612 = 100%
Total lines: 1756
Total bytes: 319612

Instead of printing that you could update your progress.

So, what is the best approach?

  • If you know that you have simple ASCII text in an encoding that uses only 1 byte for those characters: just use String#length() (and maybe add +1 or +2 for the line ending) String#length() is fast and simple and as long as you know what files you have you should have no problems.
  • If your have international text where the simple approach won't work:
    • for smaller files where processing each line takes rather long: String#getBytes(), the longer processing 1 line takes the lower the impact of temporary arrays and their garbage collection. The inaccuracy should be within acceptable bounds. Just make sure not to crash if progress > 100% or < 100% at the end.
    • for larger files above approach. The larger the file the better. Updating progress in 0.001% steps is just slowing down things. Decreasing the reader's buffer size would increases the accuracy but it also decreases the read performance.
  • If you have enough time: write your own Reader that tells you the exact byte position. Maybe a combination of InputStreamReader and BufferedReader since Reader already operates on characters. Android's implementation may help as starting point.
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ get-size-in-bytes-of-string-java
How to Determine the Size in Bytes of a String in Java? - CodingTechRoom
String str = "Hello, World!"; byte[] byteArray = str.getBytes(StandardCharsets.UTF_8); int byteSize = byteArray.length; // Size in bytes ยท In Java, calculating the size in bytes of a String can be done using the `getBytes` method.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ how to get the size of an object in java
How to Get the Size of an Object in Java | Baeldung
January 8, 2024 - Unlike C/C++ where we can use sizeof() method to get an object size in bytes, thereโ€™s no true equivalent of such method in Java.
๐ŸŒ
Rosetta Code
rosettacode.org โ€บ wiki โ€บ String_length
String length - Rosetta Code
2 weeks ago - Calculating "Byte-length" (by which one typically means "in-memory storage size in bytes") is not possible through the facilities of the Groovy language alone. Calculating "Character length" is built into the Groovy extensions to java.lang.String.
๐ŸŒ
Mother Eff
mothereff.in โ€บ byte-counter
UTF-8 string length & byte counter
Pro tip: add http://mothereff.in/byte-counter#%s to the custom search engines / location bar shortcuts in your browser of choice. Whenever I want to check string length / byte count, I just enter len some string in my address bar.
๐ŸŒ
Araqev
araqev.com โ€บ home โ€บ how many bytes are in a string? understanding string storage in programming
How Many Bytes Are in a String? Understanding String Storage in Programming
March 22, 2025 - โ€œWhen calculating the byte size of a string, one must also consider any additional metadata associated with the string in certain programming languages. For example, languages like Java may include overhead for object representation, which can affect the total byte count.โ€
๐ŸŒ
Hgko1207
hgko1207.github.io โ€บ 2021 โ€บ 03 โ€บ 10 โ€บ java-dev-6
[JAVA] Stringํ˜• Bytes length ๊ตฌํ•˜๊ธฐ | ๊ทœ๋‹ˆ์˜ ๋ธ”๋กœ๊ทธ
January 18, 2024 - ๊ธฐ๋ณธ ์ธ์ฝ”๋”ฉ์ด UTF-8 ์„ค์ •๋˜์–ด์žˆ์„ ๊ฒฝ์šฐ ํ•œ๊ธ€์€ ํ•œ๊ธ€์ž๋‹น 3๋ฐ”์ดํŠธ์”ฉ ๊ณ„์‚ฐ๋ฉ๋‹ˆ๋‹ค. ํ•œ๊ธ€ ํ•œ๊ธ€์ž๋‹น 2๋ฐ”์ดํŠธ์”ฉ ๋‚˜์˜ค๊ฒŒ ํ•˜๋ ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ธ์ฝ”๋”ฉ์„ ์„ค์ •ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค ยท Impeccable ๋””์ž์ธ ์›์น™ ...
๐ŸŒ
Quora
quora.com โ€บ How-many-bytes-is-a-string-For-example-how-long-is-Hello-World-Is-its-length-the-same-as-the-number-of-bytes-that-it-consists-of
How many bytes is a string? For example, how long is 'Hello World'? Is its length the same as the number of bytes that it consists of? - Quora
Answer (1 of 5): The number of bytes occupied by a string of characters depends on the character encoding scheme being used, and on how the string object is represented internally in your specific environment. In this answer, weโ€™ll assume that a byte is eight bits wide.