Reverse words in string in Java

Learn to reverse each word in a sentence in Java with example. We will reverse words in string in place using StringBuilder and StringUtils classes.

Original String – how to do in java

Reverse words – woh ot od ni avaj

1. Reverse words in string – StringBuilder class

  • Tokenize each word using String.split() method.
  • Loop through string array and use StringBuilder.reverse() method to reverse each word.
  • Join all revered words to get back string.
String blogName = "how to do in java";
StringBuilder reverseString = new StringBuilder();

String[] words = blogName.split(" ");		//step 1

for (String word : words) 
    String reverseWord = new StringBuilder(word).reverse().toString();		//step 2
    reverseString.append(reverseWord + " ");								//step 3

System.out.println( reverseString.toString().trim() );		//verify reversed string

Program output.

woh ot od ni avaj

2. Reverse words in string – StringUtils class

StringUtils class is in Apache command lang library. Use it’s StringUtils.reverseDelimited() method to reverse each word and join the string.

String blogName = "how to do in java";

String reverseString = StringUtils.reverseDelimited( StringUtils.reverse(sentence), ' ' );

System.out.println( reverseString );

Program output.

woh ot od ni avaj

In this post, we learned to reverse each word in a sentence in Java.

Happy Learning !!

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

5 thoughts on “Reverse words in string in Java”

    • // this is a little hard coded, you can’t use StringBuilder for this task
      String original = “Hi John”;
      String [] split = original.split(” “);
      String result = split[1] + ” ” + split[0];

    • store it in character array .Overwrite accordance with reversal using INDEX OF CHARACTERS
      Here below is your program:-

      import java.util.Scanner;
      public class Reverse
      	public static void main(String args[])
      		Scanner sc=new Scanner(;
      		System.out.println("Enter the string:");
      		String s = sc.nextLine();
      		int l = s.length();
      		char ch[] = s.toCharArray();
      		for(int i=l-1; i>=0; i--)

Leave a Comment


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