Make Selenium Easy

Frequently Asked Java Program 19: Java Program to Reverse Position of Words in a String

Problem statement:

Write a Java program to reverse position of words in given string i.e. word at first position in string should be at last position in string.

Input String: You are awesome
Output String: awesome are You


It is a very easy program. You just need understanding of splitting a string, array and for loop to traverse string in reverse direction.

Steps to follow:

Step 1: First of all we need to extract words from a given string. Two words are separated by while space. We can use split() method given by String class which splits a string by provided delimiter and returns a String[] of splitted words. For example:


Step 2: Traverse from end to first position and print array content. 

Java Program:

package StringPrograms;

import java.util.Scanner;

public class ReverseStringByPositionOfWords {

	 * This method splits given string by space delimiter and returns a String
	 * array.
	public static String[] splitStringBySpace(String inputStringToSplit) {
		return inputStringToSplit.split(" ");

	public static void main(String[] args) {

		// User input for the string to know length
		Scanner sc = new Scanner(;
		System.out.println("Please enter the string to reverse each word:");

		String userInput = sc.nextLine();

		// Split string
		String[] splitedString = splitStringBySpace(userInput);
		// Output with each word reversed
		String desiredString="";
		// Reversing word by word and appending
		for(int j=splitedString.length-1;j>=0;j--)
			desiredString= desiredString + splitedString[j] +" ";
		System.out.println("Original string            :"+userInput);
		System.out.println("String with reversed words :"+desiredString);


Hopefully, you got the logic to solve above problem. If you have any doubt, kindly comment.


Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

Frequently Asked Java Program 19: Java Program to Reverse Position of Words in a String

by Amod Mahajan time to read: 1 min
%d bloggers like this: