The following code reverses the order of words in a String. First it breaks the string into the words using StringTokenizer and reverses the order of the words using LIFO property of Stack.

 import java.util.*;

public class StringReverseWord {

    private static void doStringReverseWord() {
        String a = "Rohit Khariwal Mohit Parnami";
        Stack  stack = new Stack();

        // this statement will break the string into the words which are separated by space.
        StringTokenizer tempStringTokenizer = new StringTokenizer(a);

        // push all the words to the stack one by one
        while (tempStringTokenizer.hasMoreTokens()) {

        System.out.println("\nOriginal string: " + a);

        System.out.print("Reverse string: ");
       // pop the words from the stack
        while(!stack.empty()) {
            System.out.print(" ");


      public static void main(String[] args) {


Output Screen:

Original string: Rohit Khariwal Mohit Parnami
Reverse string: Parnami Mohit Khariwal Rohit