Scrivio Interview library

Strings and text

41 questions in 14 subtopics.

Immutability

ConceptFoundations7 min read
Why is String immutable in Java? Give at least four concrete benefits and one cost.
CodingFoundations5 min read
What does this print and why?
String s = "java";
s.toUpperCase();
s.concat("21");
System.out.println(s);
InternalsIntermediate7 min read
Before JDK 7u6, String.substring shared the parent's char array. Why was that changed, and what does substring cost today?
ScenarioIntermediate7 min read
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?
ConceptPrincipal7 min read
String has been final and immutable since Java 1.0. Explain why that early decision still shapes security, performance and API design in the platform, and what lesson it offers for designing core types in your own organization.

String pool and intern

CodingFoundations6 min read
What do these comparisons print?
String a = "hello";
String b = "hel" + "lo";
String c = new String("hello");
String part = "hel";
String d = part + "lo";
System.out.println((a == b) + " " + (a == c) + " " + (a == d) + " " + (a == d.intern()));
InternalsIntermediate6 min read
Where does the string pool live in modern JDKs, how does intern() work, and when is calling it a good or bad idea?
ScenarioAdvanced6 min read
A fleet of services loads large JSON product catalogs, and heap dumps show 30 percent of heap is duplicate strings such as category names and currency codes. What fleet-wide options do you evaluate?
ConceptPrincipal6 min read
Over Java's history the string pool moved from PermGen to the heap, String gained compact storage, and the collectors gained string deduplication. What does that sequence suggest about where memory optimisations for text belong: in application code or in the platform? How would you guide teams?

StringBuilder vs StringBuffer

ConceptFoundations5 min read
Compare String, StringBuilder and StringBuffer. When would you still use StringBuffer?
CodingFoundations6 min read
Rewrite this for performance and explain the cost of the original:
String csv = "";
for (String item : items) {
csv += item + ",";
}
InternalsIntermediate7 min read
How does StringBuilder grow its buffer, and what are the consequences for building very large strings, such as a 500 MB report?

Compact strings

InternalsIntermediate6 min read
Explain compact strings (JEP 254, JDK 9). How is a String stored, what is the coder field, and when can compact strings hurt?
ScenarioAdvanced7 min read
After a Java 8 to 17 migration, heap usage dropped noticeably for most services but not for one service that serves Japanese and Chinese content. Engineers ask whether something is misconfigured. How do you explain and act?

String concatenation and invokedynamic

InternalsIntermediate6 min read
How is "id=" + id + ", name=" + name compiled in JDK 8 versus JDK 9 and later, and why did the change matter?
DesignAdvanced6 min read
A team writing a logging-heavy library asks whether to build messages eagerly with + or to pass format strings with arguments. What is your guidance and why?

Text blocks

CodingFoundations6 min read
Write a JSON request body as a text block and explain how incidental indentation and the closing delimiter position affect the result.
ScenarioIntermediate6 min read
A team embeds large SQL statements as text blocks and inserts user values with .formatted(). What issues do you raise in review?

Formatting and String.format

CodingFoundations6 min read
Why can String.format("%.2f", 1234.5) print "1234,50" on some servers, and how do you make output stable?
ConceptIntermediate6 min read
Compare String.format, String.formatted, MessageFormat, DecimalFormat and plain concatenation for building strings in a service. Which are thread-safe and which are costly?

Charset and encodings

DebuggingFoundations7 min read
A file written on a Linux server shows garbled accented characters when read on an older Windows build agent. The code uses new String(bytes) and FileReader without a charset. Explain and fix it.
ConceptIntermediate7 min read
A column limit is 255 characters, but an insert of a 200-character name fails. Explain the difference between chars, code points, grapheme clusters and bytes, and the Java APIs for each.
LeadershipAdvanced7 min read
Your company runs services on JDK 8, 11, 17 and 21. You want to make UTF-8 the guaranteed encoding everywhere. What is your plan and what risks do you look for?
LeadershipPrincipal7 min read
Java's default charset was platform-dependent for over twenty years before JDK 18 made UTF-8 the default. What does this history teach about platform defaults, and what defaults would you standardise for text across your organization's services, data stores and APIs?

Regular expressions with Pattern and Matcher

CodingFoundations6 min read
What is wrong with this hot-path code and how do you fix it?
boolean valid(String s) {
return s.matches("[A-Z]{3}-\\d{4}");
}
DebuggingFoundations6 min read
Why does "a.b.c".split(".") return an empty array, and why does text.replaceAll("$price", value) fail?
DebuggingIntermediate9 min read
A request with a long input string pegs a CPU core at 100 percent inside java.util.regex. The pattern is ^(\w+\s?)*$. Explain the cause and the fixes.
DesignAdvanced8 min read
You are designing a shared input validation library for many teams. What rules do you set for regular expressions?

String templates status

ConceptIntermediate7 min read
What happened to string templates (STR."...") in Java, and what should teams use instead in Java 25?
LeadershipPrincipal7 min read
String templates were previewed in two releases and then withdrawn. What does this teach about how Java evolves, and what policy would you set on preview features for a large organization?

String API methods

ConceptFoundations7 min read
Explain the difference between these String methods and the common bugs with each: replace vs replaceAll, indexOf vs contains, equals vs equalsIgnoreCase vs compareTo, substring(begin, end), and chars() vs codePoints().
ConceptFoundations6 min read
What does each line print, and why?
String s = "\u2003 hi \t";
System.out.println(s.trim().length());
System.out.println(s.strip().length());
System.out.println(" ".isBlank() + " " + "".isEmpty());
System.out.println("ab".repeat(3));
System.out.println("a\nb\r\nc".lines().count());
ScenarioIntermediate6 min read
In a code review you find a StringUtils class in your service with 40 hand-written helpers (isNullOrEmpty, padLeft, capitalize, join, reverse, countMatches), and three other libraries offering the same. What do you recommend, given what the JDK String API now provides?

Splitting and joining strings

ConceptFoundations7 min read
What do these return, and why?
"a,b,,c,,".split(",").length
"a,b,,c,,".split(",", -1).length
",a,b".split(",").length
"a1b22c".split("\\d+")
String.join("-", List.of("x", "y", "z"))
Then show two other ways to join a list of strings with a prefix and suffix.
DebuggingIntermediate8 min read
An import job parses CSV lines with line.split(","). Customers report wrong columns for addresses such as "Main St, Apt 4" and for names with quotes, and the job is slow on 50 million lines. Explain the problems and what you would use instead.

Locale and internationalization

DebuggingFoundations7 min read
A service checks permissions with if (header.toUpperCase().equals("TITLE")). It works everywhere except on a server whose default locale is Turkish (tr-TR), where the check fails. Explain why and how to fix this and similar bugs.
DebuggingIntermediate8 min read
After upgrading from JDK 17 to JDK 21, a service that parses times like "3:30 PM" with DateTimeFormatter.ofPattern("h:mm a", Locale.US) starts throwing DateTimeParseException for input from a partner, and some formatted output looks different. Explain the likely cause and how you handle locale data changes in upgrades.
DesignAdvanced8 min read
Your product is expanding from English-only to 12 languages, including German, Japanese and Arabic. The Spring Boot backend builds emails, PDFs and error messages with string concatenation. What do you design for internationalization in the backend, and what do you require from teams?

Escaping and encoding text

DebuggingFoundations8 min read
A service builds a redirect URL with "https://shop.example/search?q=" + URLEncoder.encode(term, UTF_8) and a file path with "/files/" + URLEncoder.encode(name, UTF_8). Search for "a b" works, but a file named "my report.pdf" returns 404. Explain, and describe when to use URL encoding, HTML escaping and Base64.
ScenarioIntermediate8 min read
A security review of a Spring Boot service finds: user input written to logs without filtering, error messages that echo request parameters into HTML, JSON built with string concatenation, and SQL built with String.format and a home-made escape function. Explain the risk of each and the correct fix.
LeadershipAdvanced7 min read
Across 80 services, security incidents keep coming from wrong or missing output encoding: XSS in admin pages, CSV formula injection in exports, and log forging. How would you make correct escaping the default across teams instead of relying on each developer?