Debug a Java CSV Export Function for Output and Performance Bugs
MercorSoftware Engineer · Technical ScreenLast updated
A debugging exercise on a small Java function that converts rows of string fields into CSV text for import by another system. You find what is wrong with its output and why it slows down sharply on large exports, then fix it. It tests string handling, the cost of building strings in loops, and edge-case tests.
You are given a small Java utility that turns a table of string fields into CSV text for another system to import, and it is used for large exports. Find what is wrong with the output it produces and with how it performs on large inputs, explain why each problem happens, and fix the function.
The original code from the interview was not reported; the function below is a representative reconstruction of the code under review.
import java.util.List;
public class CsvExporter {
/**
* Returns the rows as CSV text: one line per row, fields separated by
* single commas, every line terminated by '\n'.
*/
public static String toCsv(List<List<String>> rows) {
String result = "";
for (List<String> row : rows) {
for (String field : row) {
result += field + ",";
}
result += "\n";
}
return result;
}
}
For the rows ["id", "name"] and ["1", "Ada"], the intended output is the following, with a line break after each line, including the last:
id,name
1,Ada
Constraints and Clarifications
- Assume fields contain no commas, double quotes or line breaks, so no quoting is needed; quoting is a follow-up.
- Fields are never
null. - Exports can be large enough that running time matters.
Clarifying Questions
- Does the importing system expect a line break after the last line?
- What should an empty row produce: an empty line, or nothing at all?
- Is the first row a header, and must every row have as many fields as the header?
- Must the result be one in-memory string, or may the function write to a stream instead?
Hints
Hint 1
Trace it by hand: Run the function mentally on the two-row example and compare its result with the intended output character by character, paying attention to the end of each line.
Hint 2
Count the copying: Java strings are immutable. Think about what `+=` must do with the characters already in `result` each time the loop body runs, and how that work adds up as the output grows.
Follow-up questions
- A field contains a comma or a double quote. What does your function produce, and how should it be fixed?
- The export is too large to hold in memory as one string. How would you change the function's interface?
- Does the Java compiler turn `+=` inside a loop into a `StringBuilder` for you? Why does the problem remain?
- How would you write a test that catches the performance problem, not just the formatting one?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.