Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service holds passwords and API secrets in String fields and logs request objects with toString. A security review flags it. What do you change and why?

Two things need to change. First, secrets must never reach the logs: we give request objects a toString() that masks secret fields, or better, hold secrets in a small wrapper type whose toString() always prints a mask. Second, we shorten how long secrets live in memory: Strings are immutable and cannot be wiped, so APIs that take char[] let us overwrite the value after use, and we protect heap dumps and prefer short-lived secrets from a secret manager.

Why this question is asked

Security reviews flag this pattern often because it combines two separate risks. The logging risk is concrete and common: one log.info("request {}", request) call can copy a password into a log system that hundreds of people and several vendors can read, and logs are kept for months. The memory risk is subtler: anyone who obtains a heap dump can read every String in it. Interviewers ask this as a scenario to see whether we can rank those risks and fix them properly rather than recite that char[] is better than String. In this answer, we will see why a String cannot be cleared, fix the logging leak, look at where char[] really helps, and then deal with heap dumps and secret lifetime.

1Why a String Secret Cannot Be Erased

A String is immutable: once created, its characters never change. That is great for safety in most code, but it means there is no way to overwrite a password held in a String when we are done with it. The characters stay in the heap until the garbage collector reclaims the object, and even then the memory is not zeroed until something else is written over it.

It gets worse because strings are copied freely. Every concat, substring, toLowerCase or trim creates another copy, frameworks copy them while parsing JSON or HTTP headers, and a moving collector copies objects between regions. We may have several copies of one secret scattered across the heap without ever writing code that makes them.

Java
String password = request.getPassword();
authenticate(user, password);
password = null; // only drops our reference; the characters are still in the heap
char[] pin = console.readPassword("PIN: "); // Console returns char[] on purpose
try {
verify(pin);
} finally {
Arrays.fill(pin, '\0'); // the characters are overwritten right now
}

Setting a variable to null only removes one reference. With a char[] we can actually overwrite the contents, which is why Console.readPassword, JPasswordField.getPassword(), KeyStore.load(InputStream, char[]) and KeyStore.PasswordProtection all use char arrays. The JDK designers wanted the caller to be able to wipe the secret as soon as it is no longer needed.

2Fixing the Bigger Leak First: toString and Logs

The review finding that matters most is the logging. The service logs request objects, and the default toString() of a record, or one generated by Lombok or an IDE, prints every field. Here is the failure.

Java
public record LoginRequest(String user, String password) { }
log.info("login attempt {}", new LoginRequest("ann", "s3cret!"));
// login attempt LoginRequest[user=ann, password=s3cret!]

Notice that nobody wrote code to log the password. It leaked because a generic toString() included it. Fixing it at each log call does not scale, because the next developer will log the object again. The fix belongs in the type itself.

3Fix: A Secret Type That Cannot Print Itself

The most robust fix is to stop using String for secrets in our own model and use a tiny wrapper. Its toString() always prints a mask, so whatever logs it, whether our code, a framework or an exception message, gets the mask. Getting the real value requires an explicit call that is easy to search for in code review.

Java
public final class Secret {
private final char[] value;
public Secret(char[] value) { this.value = value.clone(); }
public char[] reveal() { return value.clone(); } // explicit, easy to grep for
public void wipe() { Arrays.fill(value, '\0'); }
@Override public String toString() { return "****"; }
}
public record LoginRequest(String user, Secret password) { }
log.info("login attempt {}", new LoginRequest("ann", new Secret("s3cret!".toCharArray())));
// login attempt LoginRequest[user=ann, password=****]
Step throughWhere a logged secret can leak
  1. Request object loggedlog.info("{}", request)
  2. toString() prints all fields?
    YesSecret in the log lineNoMask printed instead
  3. Log shipped to central storekept for months, many readers
  4. Secret type with masking toString()stops the leak at the source

4 steps in order. Play them, or step through them one at a time.

The fix belongs in the type, so every log call and framework gets the mask.

The record's generated toString() now calls Secret.toString() for the password and prints the mask. If we cannot change the field type, we override toString() in the record or class, or use Lombok's @ToString.Exclude, and we add @JsonIgnore or a masking serializer so that JSON request logging does not bypass toString(). Many teams also add a log-pattern mask for things that look like tokens, as a second line of defence, but it should never be the only one. Spring Boot 3 helps on its side too: the actuator env and configprops endpoints mask values by default (see management.endpoint.env.show-values, and check your version).

4Heap Dumps Are Secrets Too

Even with perfect logging, a heap dump contains every live String in the process, including tokens and passwords. Services are often configured with -XX:+HeapDumpOnOutOfMemoryError, and the dump file lands on a disk or in a ticket attachment. A dump of a 4 GB heap is a 4 GB file that may hold every customer token the service had in memory.

So we treat heap dumps as sensitive data: write them to a directory only the service account can read (-XX:HeapDumpPath), restrict who can run jcmd GC.heap_dump in production, keep them out of shared tickets, encrypt them at rest and delete them after the analysis. This is a process fix, not a code fix, but the review should list it.

5Shorter-Lived Secrets

The last improvement is to reduce what an attacker gains from any single leak. A database password read once at startup and held in a String for the life of the process is valuable for months. A short-lived token, fetched from a secret manager such as HashiCorp Vault or a cloud secret service and rotated every hour, is worth much less if it shows up in a dump next week.

It is worth being honest about the limits of char[] here. HTTP and JSON libraries almost always hand us secrets as Strings already, so converting to char[] later does not erase the earlier copies. That is why I rank the fixes this way: masking in logs first, because that leak is common and long-lived; heap dump handling second; short-lived secrets third; and char[] where the API supports it, as a good habit that narrows the window rather than closing it.

6Follow-up questions

Is char[] really safer if the JIT or GC can copy arrays too?

Somewhat. A moving collector can leave an old copy of the array behind, so wiping the array does not guarantee no copy exists anywhere. But it shrinks the window: the live object is cleared immediately and no new copies are made from it. With a String we cannot even do that. It is a mitigation, not a guarantee, which is why log masking and dump handling matter more.

What about exceptions that include the secret in their message?

That is a real leak path. Code such as throw new IllegalArgumentException("bad key " + key) puts the secret into the message, the stack trace and every log that prints it. Review rules should forbid putting secret values in messages, and the Secret wrapper helps because concatenating it prints the mask.

How would you test that secrets never reach the logs?

Write a test that runs the main request flows with a known fake secret such as TEST-SECRET-123, captures the log output with an in-memory appender, and fails if the string appears anywhere. It catches regressions when someone adds a new log line or a new field.

7Conclusion

In this answer, we saw that a String holding a secret cannot be wiped, may be copied many times and lives until garbage collection, which is why JDK security APIs use char[] so callers can overwrite it. The more urgent problem in the scenario was logging: generic toString() methods print every field, so we moved secrets into a wrapper type whose toString() masks the value and kept JSON logging from bypassing it. We then treated heap dumps as sensitive data and preferred short-lived secrets from a secret manager.

What to say in the interviewAbout 90 seconds aloud

Open with

I would fix the logging first, because that is the leak that actually happens. A record or Lombok toString prints every field, so logging a request object writes the password into a log store that many people can read for months.

Then, if they want more

Rather than patching each log call, I would put secrets in a small wrapper type, say Secret, whose toString always returns stars and which only gives the value through an explicit reveal method.

Where I cannot change the type, I override toString or exclude the field, and I make sure JSON request logging masks it too, and I add a test that runs the main flows with a fake secret and fails if it appears in the captured logs. Second, memory.

Strings are immutable, may be copied by frameworks and by the collector, and stay in the heap until they are collected, so I cannot erase them. That is why APIs like KeyStore and JPasswordField take char arrays, which I can fill with zeros in a finally block.

I would use those where the API allows, while being honest that the HTTP layer has probably made a String copy already. So third, I treat heap dumps as sensitive: restricted paths and access, no attaching them to tickets, deletion after analysis.

And finally I would prefer short-lived secrets from a secret manager, so any copy that does leak expires quickly.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3
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.
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 "A service holds passwords and API secrets in String fields and logs request objects with...": https://scrivio-interview-library.netlify.app/java/strings/9d8f5a4e36/