Quick revision
The short answer
Between byte[] and String we always name the charset: new String(bytes, StandardCharsets.UTF_8) and s.getBytes(StandardCharsets.UTF_8), because the platform default used to vary by machine and has only been UTF-8 since Java 18 (JEP 400). Between char[] and String we use new String(chars) or String.valueOf(chars), and s.toCharArray(), which returns a copy. Passwords are kept in char[] because we can overwrite the array with Arrays.fill when we are done, while an immutable String stays in memory until the garbage collector reclaims it; the benefit is limited, but APIs such as Console.readPassword return char[] for this reason.
What to remember
In this answer, we saw that bytes become text only through a charset, so we always pass one: new String(bytes, StandardCharsets.UTF_8) and s.getBytes(StandardCharsets.UTF_8), because the platform default varied before UTF-8 became the default in Java 18 with JEP 400. The String constructor silently replaces invalid bytes, so we use a CharsetDecoder with CodingErrorAction.REPORT when validity matters, and we encode binary data with Base64 instead of treating it as text. char[] and String convert directly with copies, and passwords sit in char[] so we can erase them with Arrays.fill, a real but limited benefit that APIs such as Console.readPassword are built around.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Between byte[] and String we always name the charset: new String(bytes, StandardCharsets.UTF_8) and s.getBytes(StandardCharsets.UTF_8), because the platform default used to vary by machine and has only been UTF-8 since Java 18 (JEP 400). Between char[] and String we use new String(chars) or String.valueOf(chars), and s.toCharArray(), which returns a copy. Passwords are kept in char[] because we can overwrite the array with Arrays.fill when we are done, while an immutable String stays in memory until the garbage collector reclaims it; the benefit is limited, but APIs such as Console.readPassword return char[] for this reason.
Why this question is asked
Converting between bytes and text is one of the most common sources of quiet data corruption: names that turn into question marks, files that read fine on a laptop and break on a server, and binary data that is mangled by being treated as text. Interviewers ask this question because getting it right requires understanding the difference between bytes and characters, and the password part checks whether we can reason about security claims honestly. In this answer, we will recap bytes, characters and charsets, convert correctly in each direction, see what happens with invalid input and how to detect it, deal with binary data, and then look at the char[] password advice and its limits.
1A Quick Recap: Bytes, Characters and Charsets
A byte[] is raw data, numbers from -128 to 127. A String is a sequence of characters. A charset is the rule that turns one into the other. In UTF-8, the letter A is one byte (65), while the letter e with an acute accent is two bytes, and many Chinese characters are three. In ISO-8859-1, every character is exactly one byte, and many characters cannot be represented at all.
So the same bytes can mean different text depending on the charset used to read them, and converting text to bytes with one charset and back with another corrupts it. A char[] is different: it already holds characters (UTF-16 code units, strictly speaking), so converting between char[] and String needs no charset at all.
2Converting Between byte[] and String
The safe pattern is to name the charset in both directions, using the constants in StandardCharsets so there is no lookup by name and no checked exception.
The last line is the trap. Without an argument, getBytes and new String(bytes) use the platform default charset. Before Java 18, that default came from the operating system's locale, so the same code produced different bytes on a developer's Mac, a Windows build agent and a Linux server with a POSIX locale. JEP 400 made UTF-8 the default in Java 18, which removes most surprises on new JVMs, but code that names the charset explicitly is correct on every version and tells the reader what format the data is in. Static analysis tools flag the default-charset calls for this reason.
3Invalid Bytes Are Replaced Silently
If the bytes are not valid in the charset, the String constructor does not throw. It replaces each bad sequence with the replacement character U+FFFD, and our data is corrupted without any warning. When we must know that the input was valid, for example when reading a file that claims to be UTF-8, we use a CharsetDecoder configured to report errors.
MalformedInputException is a subclass of CharacterCodingException, a checked IOException, so the caller has to decide what to do with bad input, which is exactly the point.
4Binary Data Is Not Text
A hash, an encrypted token or an image is arbitrary bytes, not encoded text. Turning it into a String with new String(bytes, UTF_8) replaces every invalid sequence with U+FFFD, and converting back does not return the original bytes, so a signature or a key is destroyed. To carry binary data as text, for example in JSON or a header, we encode it with Base64.
| We have | We want | Use |
|---|---|---|
| String | byte[] text | s.getBytes(StandardCharsets.UTF_8) |
| byte[] text | String | new String(bytes, StandardCharsets.UTF_8) |
| byte[] text, must be valid | String or error | CharsetDecoder with CodingErrorAction.REPORT |
| char[] | String | new String(chars) or String.valueOf(chars) |
| String | char[] | s.toCharArray(), returns a copy |
| binary byte[] | text | Base64.getEncoder().encodeToString(bytes) |
5Converting Between char[] and String
Since char[] already holds characters, the conversion is direct. new String(chars) and String.valueOf(chars) both create a String with a copy of the characters, so later changes to the array do not affect the String. s.toCharArray() creates a new array each time, so changing it does not affect the String either. Both directions copy, which matters for the password discussion that follows.
6Why Passwords Are Kept in char[], and the Limits of That
A String is immutable. Once a password is in a String, we cannot erase it; it stays in the heap until the garbage collector reclaims that memory and something else overwrites it, which may take a long time. Meanwhile it can appear in a heap dump, a core dump or a debugger. A char[] can be overwritten as soon as we are done with it.
This is why Console.readPassword, KeyStore.load and PBEKeySpec take or return char[]. But we should be honest about the limits. The benefit disappears the moment any code calls new String(password), which many libraries and frameworks do, or the moment the password arrived as a String in an HTTP request body. The garbage collector may also have copied the array before we cleared it, leaving old copies in memory. So char[] narrows the window of exposure; it is a useful habit, not a guarantee, and protecting heap dumps and memory access matters more.
7Follow-up questions
Is String.getBytes() without a charset fine on Java 21 or 25?
It uses UTF-8 by default since Java 18, so it usually works, but the default can still be changed with the file.encoding system property, and the code hides its assumption from readers. Naming StandardCharsets.UTF_8 costs nothing and is correct on every version.
What happens if we convert text with a charset that cannot represent it?
getBytes replaces unmappable characters with a substitute, a question mark for ISO-8859-1, so the data is lost silently. A CharsetEncoder with CodingErrorAction.REPORT throws instead, which is the right choice when losing characters is not acceptable.
Does a String store its text as UTF-8 internally?
No. Since Java 9, compact strings store a String that contains only Latin-1 characters as one byte per character in an internal byte[], and switch to two bytes per character (UTF-16) only when needed. That is an internal detail of String and does not change how we convert to and from byte[].
8Conclusion
In this answer, we saw that bytes become text only through a charset, so we always pass one: new String(bytes, StandardCharsets.UTF_8) and s.getBytes(StandardCharsets.UTF_8), because the platform default varied before UTF-8 became the default in Java 18 with JEP 400. The String constructor silently replaces invalid bytes, so we use a CharsetDecoder with CodingErrorAction.REPORT when validity matters, and we encode binary data with Base64 instead of treating it as text. char[] and String convert directly with copies, and passwords sit in char[] so we can erase them with Arrays.fill, a real but limited benefit that APIs such as Console.readPassword are built around.
Open with
For bytes and strings, I always pass the charset: new String(bytes, StandardCharsets.UTF_8) and s.getBytes(StandardCharsets.UTF_8). The no-argument versions use the platform default, which used to depend on the operating system's locale, so the same code could behave differently on different machines.
Then, if they want more
Since Java 18, JEP 400 made UTF-8 the default, but naming it is still clearer and works on every version. I'd also mention that the String constructor never throws on bad input; it silently replaces invalid sequences with the replacement character, so if I need to reject invalid data I use a CharsetDecoder with CodingErrorAction.REPORT, which throws MalformedInputException.
And binary data like hashes or encrypted values is not text at all, so I'd Base64-encode it rather than calling new String on it, because that destroys the bytes. For char[] it's simpler: new String(chars) or String.valueOf, and toCharArray, all of which copy.
Passwords go in char[] because Strings are immutable: I can't erase one, so it stays in the heap until it's collected and could show up in a heap dump. With a char[], I can Arrays.fill it with zeros right after use, which is why Console.readPassword returns char[].
But it's a limited benefit: if any code turns it into a String, or the GC already copied the array, the protection is gone.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 18, Java 17, Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How do you convert between byte[] and String, and between char[] and String, correctly?...": https://scrivio-interview-library.netlify.app/java/arrays/de55835c38/