Java Program - String Reversal¶
Concept Explanation¶
What is it?¶
String reversal is the process of rearranging the characters of a string in the opposite order. For example, "Hello" becomes "olleH".
Why is it important?¶
It is a fundamental algorithm used in data processing, palindromic checks, and interview coding challenges.
Algorithm (Manual Method)¶
- Start
- Input a string
str. - Create an empty string
reversed. - Loop through
strfrom the last character back to the first. - Append each character to
reversed. - Display
reversed. - End
Implementations¶
import java.util.Scanner;
public class StringReversal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
// Method 1: Using StringBuilder (Easy & Efficient)
String reversedSB = new StringBuilder(str).reverse().toString();
// Method 2: Manual Loop
String reversedManual = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversedManual += str.charAt(i);
}
System.out.println("Original: " + str);
System.out.println("Reversed (StringBuilder): " + reversedSB);
System.out.println("Reversed (Manual Loop): " + reversedManual);
sc.close();
}
}
Explanation¶
- Java
- StringBuilder: A mutable sequence of characters. Its
.reverse()method is the most efficient way to reverse a string in Java. - charAt(i): Returns the character at index
i. - Efficiency: In the manual loop,
reversedManual += str.charAt(i)creates many temporary string objects. In professional applications, always preferStringBuilder.
Complexity Analysis¶
- Time Complexity: O(n) where n is the length of the string.
- Space Complexity: O(n) to store the reversed string.
Practice Problems¶
Easy¶
- Check if a string is a Palindrome (reads the same forward and backward).
Medium¶
- Reverse each word in a sentence while keeping the word order the same.
Interview Tips¶
- Explain why
StringBuilderis preferred over simple string concatenation inside a loop (Immutability vs Mutability).
"Turn your strings around, and you might find a palindrome." - Anonymous