Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to display reverse of a String.

Java Code Example — String Programs

ADVERTISEMENT

Java Program to display reverse of a String.

Objective

Write a Java program to reverse a given string.

Algorithm / Approach

  1. Create a method reverse(String x) that returns a String.
  2. Inside the method, initialize an empty string rev = "".
  3. Start a for loop starting from the last index (x.length() - 1) down to 0.
  4. Extract the character at the current index using charAt(i) and concatenate it to rev.
  5. Return rev and 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 rev accumulator 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.
ADVERTISEMENT