Write a Java program to reverse a string.
Question Explanation
Reversing a string is a common programming task that tests a candidate's understanding of basic string manipulation techniques in Java. Interviewers often ask this question to evaluate a candidate's familiarity with fundamental programming concepts such as loops, recursion, and data structures. The ability to reverse a string is not just a simple exercise; it can reveal insights into a candidate's problem-solving skills, coding style, and understanding of algorithmic efficiency. Additionally, this question can lead to discussions about time and space complexity. In a real-world context, string manipulation is essential in various applications, including data parsing, user input processing, and algorithm development. Candidates should be aware of common pitfalls, such as handling edge cases like empty strings or strings with special characters. Moreover, the evolution of programming languages has made string manipulation more straightforward, but understanding the underlying mechanics remains crucial. This knowledge is foundational in software engineering and prepares candidates for more complex tasks involving data structures and algorithms.
Sample Answers
Example 1: Using StringBuilder
To reverse a string in Java, one of the most efficient methods is to use the StringBuilder class. This class provides a convenient reverse() method. Here’s how you can implement it:
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = new StringBuilder(original).reverse().toString();
System.out.println(reversed); // Output: !dlroW ,olleH
}
}
Explanation:
- StringBuilder: This class is mutable, allowing us to modify the string without creating multiple instances.
- Efficiency: The
reverse()method runs in O(n) time complexity, where n is the length of the string, making it efficient for longer strings. - Edge Cases: This method handles empty strings and strings with special characters effortlessly.
Example 2: Using a Loop
Another straightforward way to reverse a string is by using a loop. This method gives you more control over the process. Here’s a simple implementation:
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = reverse(original);
System.out.println(reversed); // Output: !dlroW ,olleH
}
public static String reverse(String str) {
StringBuilder reversed = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversed.append(str.charAt(i));
}
return reversed.toString();
}
}
Explanation:
- Looping: This method iterates through the string from the last character to the first, building a new reversed string.
- Time Complexity: The time complexity remains O(n), but it provides a clear view of the string manipulation process.
- Flexibility: This approach allows you to easily modify the logic if needed, such as skipping certain characters.
Example 3: Using Recursion
For those interested in a more advanced approach, you can reverse a string using recursion. This method demonstrates a different way of thinking about the problem. Here’s how you can do it:
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = reverse(original);
System.out.println(reversed); // Output: !dlroW ,olleH
}
public static String reverse(String str) {
// Base case: if the string is empty or has one character
if (str.isEmpty()) {
return str;
}
// Recursive case
return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
}
}
Explanation:
- Recursion: This method breaks down the problem into smaller subproblems, reversing the last character and combining it with the reversed substring.
- Time Complexity: The time complexity is still O(n), but recursion can lead to higher space complexity due to stack usage.
- Use Cases: This approach is great for demonstrating understanding of recursion and can be applied in more complex algorithms.
Keywords
Ready to practice more questions?
Explore our collection of technical interview questions from top companies.
View All Questions