Reverse a String in Java

Learn to write Java programs to reverse a String. Learn how to reverse the characters of a string and then how to reverse the words.

Java String

Learn to write Java program to reverse a String. We will first see how to reverse the string, and then we will also see how to reverse the words in the String.

It’s a common puzzle asked in Java interviews at the beginner level. Let’s memorize these solutions for quick recall.

1. Java Program to Reverse the Characters of a String

We can reverse a string by character easily, using a StringBuilder.reverse() method.

String blogName = "HowToDoInJava.com";
 
String reverse = new StringBuilder(string).reverse();
 
System.out.println("Original String -> " + blogName);
System.out.println("Reverse String -> " + reverse);

The program output:

Original String -> HowToDoInJava.com
Reverse String -> moc.avaJnIoDoTwoH

2. Java Program to Reverse the Words of a String

While reversing string content by words, the most natural way is to use a StringTokenizer and a Stack. As you are aware that Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.

String description = "Java technology blog for smart java concepts and coding practices";
 
// reverse string builder
StringBuilder reverseString = new StringBuilder();
 
// Put words from String in Stack
Stack<String> myStack = new Stack<>();
 
StringTokenizer tokenizer = new StringTokenizer(description, " ");
 
while (tokenizer.hasMoreTokens()) {
  myStack.push(tokenizer.nextToken());
}
 
//Pop each word from stack and append in builder
 
while (!myStack.empty()) {
  reverseString.append(myStack.pop() + " ");
}
 
System.out.println(reverseString.toString());

The program output:

practices coding and concepts java smart for blog technology Java 

Happy Learning !!

Source Code on Github

Leave a Comment

  1. String str = “Java technology blog for smart java concepts and coding practices”;

    List words = Arrays.asList(str.split(“\\s”));
    Collections.reverse(words);
    System.out.println(words.stream().reduce((s1, s2) -> s1 + ‘ ‘ + s2).get());

    Reply
  2. In the same document of StringTokenizer it’s mentioned that,

    “StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead”

    Nice initiative though!!! Thumbs up!!!

    Thanks,
    Dhiraj.

    Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.