Java program to reverse a string word by word

9:04 PM 4 Comments A+ a-

Program to reverse a String word by word in Java

String based programming questions are among the most asked questions in the Java interviews for the freshers as well as the experienced Java developers and Software engineers. And reversing a string word by word or characters by characters is very likely to be asked in any Java technical interview. In this post, I will be writing a program for the former i.e. for reversing a Java String word by word
For example:- 
Input String: Code In Java
Output String: Java In Code

There might be many approaches for solving this and you may want to choose based on your liking and its simplicity. 

Below is a Java program to reverse a String word by word.

public class ReverseString {

 public static void main(String[] args) {
  //Input String
  String str = "Code in Java - Programming in Java Tutorials for beginners";
  //Approach 1 : Using String Array
  String[] reverseArray = str.split(" ");
  //String to store the reversed string
  String reverseString1 = "";
  //reading each word from the reverseArray and creating the reverseString1
  for(int i = reverseArray.length-1;i >= 0;i--)
   reverseString1+= reverseArray[i] + " ";   
  System.out.println( reverseString1 );
  //Approach 2: Using StringBuilder
  StringBuilder revString = new StringBuilder();
  //String to store the reversed string
  String reverseString2 = "";
  for (int i = 0; i< reverseArray.length;i++) {
   revString.append( reverseArray[ reverseArray.length - 1 - i ]).append(' ');
  //creating String from the StringBuilder object
  reverseString2 = revString.toString();
  System.out.println( reverseString2 );
  //There might be many other approaches to this as well. Please share the same in comments.


Currently working at Symantec in Chennai. Previously worked as a Senior Software Engineer at IGATE. Loves to explore new things, loves to code and solve challenging problems with the help of it. Like any other normal person, loves to watch movies, listen to songs (specially when travelling, it is must), getting to know people, travelling and whatever makes me feel good!


Write comments
Oracle Fusion
April 4, 2017 at 12:51 PM delete

This is just the kind of information that I had been looking for a long time, once again hats off to you! Have a look at the process blogs to see more.
Oracle Fusion HCM Technical Training

January 11, 2018 at 2:57 PM delete

Thank you for sharing such a nice and interesting blog with us. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information.

Oracle Fusion Financials Online Training

January 29, 2018 at 2:20 PM delete

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well.

Oracle Fusion HCM Online Training