Java program to reverse a string word by word

9:04 PM 1 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!