Java Program to display reverse of a String.
Objective
Write a Java program to reverse a given string.
Algorithm / Approach
- Create a method
reverse(String x)that returns a String. - Inside the method, initialize an empty string
rev = "". - Start a
forloop starting from the last index (x.length() - 1) down to0. - Extract the character at the current index using
charAt(i)and concatenate it torev. - Return
revand print it from the main method.
Test.java
import java.util.Scanner;
class Test {
public String reverse(String x) {
String rev = "";
for(int i=x.length()-1; i>=0;i--) {
rev = rev + x.charAt(i);
}
return rev;
}
public static void main(String[] a)
{
Test t = new Test();
Scanner s=new Scanner(System.in);
System.out.print("Enter String: ");
String s1 = s.nextLine();
String s2 = t.reverse(s1);
System.out.print("Reverse = "+s2);
}
}
Expected Output
Enter String: Java prowess Reverse = sseworp avaJ
Explanation of the Program
- To reverse a string, we simply read it backwards. We start our loop index at the very last character (length - 1) and decrement down to 0.
- By continually appending the characters to our
revaccumulator string, the word is built in reverse order. - Note: While this approach is great for learning, in production code, using
StringBuilder.reverse()is significantly faster and more memory efficient.
Complexity
Time Complexity
O(n)
Space Complexity
O(n) - To store the new reversed string.