Share on Google+Share on Google+

Java Reverse words of the String

In this Java Tutorial section, we are going to learn how to reverse the words of the string using in Java programming language.

Reverse words of the String Java Programming

In this section, we are going to reverse the words of the string. For this, we have allowed the user to enter the string. Then we have converted the string into tokens using StringTokenizer class. After that, we have used the reverse() method of class StringBuffer which return the reverse order of the tokens.

Here is the code:

import java.util.*;
public class ReverseWords{
public static void main(String[] args){
  System.out.print("Enter the string: ");
  Scanner input=new Scanner(;
  String str=input.nextLine();
StringBuffer buffer = new StringBuffer(str);
StringTokenizer st = new StringTokenizer(buffer.reverse().toString()" ");
System.out.print("Reversed Words: ");

StringBuffer sb= new StringBuffer(st.nextToken());
System.out.print(" "+sb.reverse());


Enter the string: java is a programming language
Reversed Words: language programming a is java


Posted on: October 26, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.