Java Program to Reverse Words in String
You can reverse words in a string in Java by splitting the string with
split(" "), then reversing the array and joining the words back with spaces using a loop or StringBuilder.Examples
Inputhello world
Outputworld hello
InputJava is fun
Outputfun is Java
Inputsingle
Outputsingle
How to Think About It
To reverse words in a string, first split the string into individual words using spaces as separators. Then, reverse the order of these words and join them back together with spaces to form the reversed string.
Algorithm
1
Get the input string.2
Split the string into words using space as the separator.3
Create a new empty string or builder to hold the reversed words.4
Loop through the words array from the last word to the first.5
Add each word to the new string with a space after it.6
Return or print the reversed string after trimming extra spaces.Code
java
public class ReverseWords { public static void main(String[] args) { String input = "Java is fun"; String[] words = input.split(" "); StringBuilder reversed = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { reversed.append(words[i]).append(" "); } System.out.println(reversed.toString().trim()); } }
Output
fun is Java
Dry Run
Let's trace the input "Java is fun" through the code
1
Split the string
words = ["Java", "is", "fun"]
2
Initialize StringBuilder
reversed = "" (empty)
3
Loop from last to first word
Append "fun ", then "is ", then "Java "
4
Trim and print
Output: "fun is Java"
| Iteration | Word Added | StringBuilder Content |
|---|---|---|
| 1 | fun | fun |
| 2 | is | fun is |
| 3 | Java | fun is Java |
Why This Works
Step 1: Splitting the string
Using split(" ") breaks the sentence into words by spaces.
Step 2: Reversing the order
Looping from the last word to the first reverses the word order.
Step 3: Building the output
Appending words with spaces and trimming removes extra space at the end.
Alternative Approaches
Using Collections.reverse
java
import java.util.*; public class ReverseWords { public static void main(String[] args) { String input = "Java is fun"; List<String> words = new ArrayList<>(Arrays.asList(input.split(" "))); Collections.reverse(words); System.out.println(String.join(" ", words)); } }
This uses Java Collections to reverse the list, which is clean and readable but requires extra memory for the list.
Using recursion
java
public class ReverseWords { public static void main(String[] args) { String input = "Java is fun"; System.out.println(reverseWords(input)); } public static String reverseWords(String s) { if (!s.contains(" ")) return s; return reverseWords(s.substring(s.indexOf(' ') + 1)) + " " + s.substring(0, s.indexOf(' ')); } }
This recursive method reverses words by breaking the string but can be less efficient and harder to read.
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string and looping through words both take O(n) time where n is the length of the string.
Space Complexity
Extra space is needed to store the split words array and the output string, so O(n) space.
Which Approach is Fastest?
Using a simple loop with StringBuilder is fast and memory efficient; Collections.reverse adds overhead but improves readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with StringBuilder | O(n) | O(n) | Simple and efficient |
| Collections.reverse | O(n) | O(n) | Readable and uses built-in methods |
| Recursion | O(n^2) | O(n) | Educational but less efficient |
Use
StringBuilder to efficiently build the reversed string instead of concatenating strings directly.Beginners often forget to trim the final string, leaving an extra space at the end.