How to reverse each word of a string in Java

Java program to reverse each word of a string:

In this post, we will learn how to reverse each word of a string in Java. We will write a program that will take a string as input from the user, reverse each word of the string and print the final string.

Since string is immutable, we will use StringBuilder to build the final string. We can convert a StringBuilder to string by using the toString() method.

Java program:

Below is the complete program:

import java.util.Scanner;

class Main {

    public static void main(String[] args) {
        String givenString;
        Scanner scanner = new Scanner(;

        System.out.println("Enter a string: ");
        givenString = scanner.nextLine();

        StringBuilder reverseSb = new StringBuilder();
        String[] words = givenString.split("\\s");

        for (String w : words) {
            reverseSb.append(new StringBuilder(w + " ").reverse());

        String reverseString = reverseSb.toString().trim();

        System.out.println("Given string: " + givenString);
        System.out.println("Reverse string: " + reverseString);


  • givenString is the variable to hold the user input string.
  • scanner is a Scanner object to read the user input data.
  • It asks the user to enter a string. The string is read and stored in the givenString variable.
  • We can’t change a string variable in Java. String is immutable. So, we are creating a StringBuilder object to hold the final string. It is reverseSb.
  • The string is split into words. We are using \s to split the string in blank spaces. split returns an array of all the words in the caller string.
  • The for loop is running through the words in the array. For each word, it creates a StringBuilder object by appending the word with a blank space. It also calls reverse() to reverse the StringBuilder object and that object is appended to reverseSb.
  • Finally, reverseSb is converted to a string with toString() method and end spaces are removed with trim(). We have to use trim() because with each word, we are adding a blank space.
  • The last two lines are printing the original string and the final reverse string.

Sample output:

If you run the above program, it will print output as like below:

Enter a string: 
hello world!!
Given string: hello world!!
Reverse string: olleh !!dlrow

Enter a string: 
hello world hello universe
Given string: hello world hello universe
Reverse string: olleh dlrow olleh esrevinu

Java reverse each word of a string

You might also like: