Home » Java programs » Java String programs

Java program to reverse words of a string

In this java program, we are going to learn how to reverse words of a string? Here, we have a string and print string by changing the order of words.
Submitted by IncludeHelp, on November 01, 2017

Given a string and we have to reverse words using java program.


Input:  I Love My Country
Output:  Country My Love I


import java.util.Scanner;
import java.util.StringTokenizer;

public class ReverseByWord 
	public static void main(String[] args) 
		// create object of the string.
		String S;
		Scanner scan = new Scanner (System.in);
		// enter your string here.
		System.out.print("Enter the string : ");
		// will read string and store it in "S" for further process.
		S = scan.nextLine();
		StringTokenizer st = new StringTokenizer(S, " ");

		// strReverseLine is the function used to reverse a string.
		String strReversedLine = "";
				strReversedLine = st.nextToken() + " " + strReversedLine;
			System.out.println("Reversed string by word is : " + strReversedLine);
		catch(Exception e)


Enter the string : I Love My Country
Reversed string by word is : Country My Love I 

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.