Reverse Words in a Sentence in Java — Definition, Examples and Program

Learn how to reverse each word in a sentence in Java while keeping the word order intact, using a character-based approach without advanced string libraries.

Reverse Words in a Sentence in Java

Reversing words in a sentence means reversing the characters of each word individually while keeping the original order of words unchanged.

This type of string manipulation is frequently asked in interviews and is useful for understanding character-level string processing.

Understanding the Problem

We do not reverse the entire sentence. Instead, each word is reversed at its own place.

Example 1

Input: Java is fun

Output: avaJ si nuf

Example 2

Input: Hello World

Output: olleH dlroW

Logic Explanation

  1. Traverse the string character by character.
  2. Store characters of a word temporarily.
  3. When a space is encountered, reverse the stored word.
  4. Append the reversed word to the result.
  5. Repeat until the end of the string.

Java Program to Reverse Words in a Sentence


import java.util.Scanner;

public class ReverseWordsInSentence {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a sentence: ");
        String str = sc.nextLine();

        String word = "";
        String result = "";

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);

            if (ch != ' ') {
                word = ch + word; // reverse the word
            } else {
                result = result + word + " ";
                word = "";
            }
        }

        // add last word
        result = result + word;

        System.out.println("Reversed words sentence: " + result);
    }
}

Sample Output


Enter a sentence: Java is fun
Reversed words sentence: avaJ si nuf

Key Points

Practice Challenges

  1. Reverse the order of words instead of characters.
  2. Handle multiple spaces between words.
  3. Rewrite the program using StringBuilder.

This program helps strengthen understanding of strings, loops, and conditional logic in Java.