Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to Reverse a String by Word using StringTokenizer and Stack class in Java ?.

Program to demonstrate how to Reverse a String by Word using StringTokenizer and Stack class in Java.

package com.hubberspot.examples;

import java.util.Stack;
import java.util.StringTokenizer;

public class ReverseWord {

	public static void main(String[] args) {

		// Create a test String which is input to the program.

		String original = "Welcome to !!!";

		// Pass the String to the StringTokenizer class which will
		// break it into tokens seperated by spaces.

		StringTokenizer stringTokenizer = new StringTokenizer(original);

		// A temp String object to hold the final reversed String by word
		String output ="";

		// Create a Stack Object. A Stack class is a special collection
		// class which stores the Object in the form of LIFO.
		// LIFO means Last In First Out. It means whichever object is 
		// added to the stack last will be removed from the collection
		// first. Stack class has methods implemented for this known as
		// push and pop.
		Stack stack = new Stack();	

		// Applying while loop over the condition (till StringTokenizer
		// has no more elements left which are seperated by tokens.


			// StringTokenizer has nextElement method which gets
			// us the next string in the class. 
			output = (String) stringTokenizer.nextElement(); 

			// Stack class push method adds the string to stack

		output = "";		

		// Till stack is empty we will loop over it
			// Stack class pop method will pop one by one 
			// last element added to the collection.
			output = output + stack.pop() + " ";

		// Printing the string over the console.
		System.out.println("\nOriginal String by word = " + original);
		System.out.println("\nReversed String by word = " + output);



Output of the program :

© 2021 Learn Java by Examples Template by Hubberspot