What are the common string reversal patterns in Java interviews, and which approach should you pick?
Three variants come up, and they have different answers. Reverse the characters of a string — use a StringBuilder and its reverse method. Reverse the words of a sentence, keeping the words themselves intact — split on whitespace, then rebuild in the opposite order. And reverse each word in place while keeping the word order — split, reverse each piece, and join again.
For the first variant, a StringBuilder is the right answer and a loop over a char array is the wrong one. The StringBuilder approach is O(n) time and O(n) space, and it is what the interviewer is looking for. The manual loop over a char array is also O(n) but it is more code and it is easy to get the boundaries wrong.
For the word variants, the trap is split behaviour. The default split on a space produces empty strings for runs of spaces, and the trailing empty strings are removed, so a sentence with a trailing space or a double space does not come back the way you expect. Passing a limit of -1 keeps every empty piece, and trimming the input first removes the leading and trailing whitespace.
The other trap is Unicode. The String methods work in UTF-16 code units, so a supplementary character such as an emoji occupies two chars and reversing the code units reverses the pair into something that is not a character at all. For text that can contain such characters, work with code points rather than chars.
One more variant worth knowing: reversing the words of a sentence in place, which needs a different technique entirely — find the start and end of each word, reverse that range, and move on. That is the question that distinguishes candidates who have only memorised the split-and-join answer.