One of the frequently asked Java interview questions is how to reverse the words in a sentence. In this tutorial, we will explore how to reverse the words in a sentence using Java. Reversing the words in a sentence means changing the order of the words so that the last word becomes the first, the second last word becomes the second, and so on.
Steps:
- Initialize a String[] words and split it using the space i.e. str.split(“” )
- Then initialize StringBuilder reverse
- Write a for loop, to add in the words in the reverse order
- Stores the words in reverse order i.e. reverse.append(words[i]).append(” “);
Java Program:
package TestAutomationCentral;
public class ReverseWords {
public static void main(String[] args) {
String str = "Test Automation Central";
String[] words = str.split(" ");
StringBuilder reverse = new StringBuilder();
for(int i=words.length-1;i>=0;i--){
reverse.append(words[i]).append(" ");
}
System.out.println(reverse.toString().trim());
}
}
Output:
Central Automation Test