Strings and text
41 questions in 14 subtopics.
Immutability
Why is String immutable in Java? Give at least four concrete benefits and one cost.What does this print and why?String s = "java";
s.toUpperCase();
s.concat("21");
System.out.println(s);
String.substring shared the parent's char array. Why was that changed, and what does substring cost today?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?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
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()));
intern() work, and when is calling it a good or bad idea?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?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
Compare String,StringBuilder and StringBuffer. When would you still use StringBuffer?Rewrite this for performance and explain the cost of the original:String csv = "";
for (String item : items) {
csv += item + ",";
}
StringBuilder grow its buffer, and what are the consequences for building very large strings, such as a 500 MB report?Compact strings
Explain compact strings (JEP 254, JDK 9). How is a String stored, what is the coder field, and when can compact strings hurt?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
How is"id=" + id + ", name=" + name compiled in JDK 8 versus JDK 9 and later, and why did the change matter?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
Write a JSON request body as a text block and explain how incidental indentation and the closing delimiter position affect the result.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
Why canString.format("%.2f", 1234.5) print "1234,50" on some servers, and how do you make output stable?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
A file written on a Linux server shows garbled accented characters when read on an older Windows build agent. The code uses newString(bytes) and FileReader without a charset. Explain and fix it.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.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?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
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}");
}
"a.b.c".split(".") return an empty array, and why does text.replaceAll("$price", value) fail?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.You are designing a shared input validation library for many teams. What rules do you set for regular expressions?String templates status
What happened to string templates (STR."...") in Java, and what should teams use instead in Java 25?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
Explain the difference between these String methods and the common bugs with each: replace vsreplaceAll, indexOf vs contains, equals vs equalsIgnoreCase vs compareTo, substring(begin, end), and chars() vs codePoints().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());
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
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"))
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
A service checks permissions withif (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.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.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
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.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.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?No question matches these choices.