Reverse String in Java – Reverse String by Words

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

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

1. Java program to reverse string

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

String blogName = "";

String reverse = new StringBuilder(string).reverse();

System.out.println("Original String -> " + blogName);
System.out.println("Reverse String -> " + reverse);

Original String ->
Reverse String -> moc.avaJnIoDoTwoH

Java Program to reverse string by words

While reversing string content by words, 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()) {

//Pop each word from stack and append in builder

while (!myStack.empty()) {
	reverseString.append(myStack.pop() + " ");



practices coding and concepts java smart for blog technology Java 

Happy Learning !!


StringBuilder.reverse() Java Doc

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

4 thoughts on “Reverse String in Java – Reverse String by Words”

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

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

  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!!!



Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.