🔹 Introduction
Reversing a string is one of the most commonly asked Java interview questions.
It helps interviewers test your understanding of strings and logic.
👉 In this article, we will learn 3 simple ways to reverse a string in Java.
🔹 Problem Statement
Given a string, reverse it.
Example:
Input: hello
Output: olleh
🔹 Approach 1: Using StringBuilder (Easiest)
This is the simplest and most commonly used approach.
🔹 Java Code (StringBuilder)
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println("Reversed String: " + reversed);
}
}
🔹 Approach 2: Using Loop (Manual Method)
This approach shows your logic-building skills.
🔹 Java Code (Using Loop)
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed String: " + reversed);
}
}
🔹 Approach 3: Using Character Array
Efficient and clean approach.
🔹 Java Code (Char Array)
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
char[] arr = str.toCharArray();
int left = 0;
int right = arr.length - 1;
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
System.out.println("Reversed String: " + new String(arr));
}
}
🔹 Time Complexity
- O(n) for all approaches
🔹 Key Takeaways
✔ StringBuilder is easiest
✔ Loop method shows strong logic
✔ Char array approach is efficient
🔹 Conclusion
Reversing a string is a basic yet important Java interview question.
Make sure you understand all approaches to confidently answer in interviews.
🔗 Also Read
👉 First Non-Repeating Character in Java
👉 Check Palindrome String in Java
Comments
Post a Comment