DEV Community

Ratik Mahajan
Ratik Mahajan

Posted on

Program to reverse a string in java

Reverse a String in java Explanation : pseudo Code

  1. Convert the string to array of characters.
  2. add all the characters to the stack
  3. create an object of the StringBuilder class and keep on adding the stack characters to the StringBuilder object.
  4. convert string builder to the string.
 public static String reverseString(String word) {
        Stack<Character> charStack = new Stack<>();
        for (char ch : word.toCharArray()) {
            charStack.push(ch);
        }
        StringBuilder sbString = new StringBuilder();
        while (!charStack.isEmpty()) {
            sbString.append(charStack.pop());
        }
        return sbString.toString();
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
mrlinxed profile image
Mr. Linxed

StringBuilder has a reverse method you could utilize, since you're already using StringBuilder.

StringBuilder input = new StringBuilder();
input.append(input);
input.reverse();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ranujmahajan profile image
Ratik Mahajan

stringBuilder reverse would also loop on the elements on the stack. i used string builder to not create many string pools in the java.