BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to reverse a String in Java Word by Word

Last Updated: June 1, 2024 by Chaitanya Singh | Filed Under: java

In this guide, we will learn how to reverse a String in java word by word. For example: If user enters a string “hello world” then the program should output “world hello”. This can be done by splitting the string into words, reversing the order of words and then joining them back together.

Program to reverse a String word by word

Let’s see the complete program. Here we are using String split() method for splitting the input string into words, then using for loop and append() method to join them back together after reversing the order.

public class ReverseWords {

public static void main(String[] args) {
String input = "Hello readers this is a Java Program";
String reversed = reverseWords(input);
System.out.println("Original: " + input);
System.out.println("Reversed: " + reversed);
}

public static String reverseWords(String str) {
// Split the string into words
String[] words = str.split(" ");

// Reverse the order of the words
StringBuilder reversedString = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedString.append(words[i]);
if (i != 0) {
reversedString.append(" ");
}
}

return reversedString.toString();
}
}

Output

Original: Hello readers this is a Java Program
Reversed: Program Java a is this readers Hello

Points to Note:

1. Multiple Spaces: If there are multiple spaces between words or before or after string then you must take care of that by trimming extra spaces. Refer: How to remove trailing spaces from a string

public class ReverseWords {

public static void main(String[] args) {
String input = " Hello readers this is Java ";
String reversed = reverseWords(input);
System.out.println("Original: \"" + input + "\"");
System.out.println("Reversed: \"" + reversed + "\"");
}

public static String reverseWords(String str) {
// Trimming the leading and trailing spaces
str = str.trim();

// This split handles multiple spaces. Use this regex.
String[] words = str.split("\\s+");

// Reverse the order of the words
StringBuilder reversedString = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedString.append(words[i]);
if (i != 0) {
reversedString.append(" ");
}
}

return reversedString.toString();
}
}

Output:

Original: "  Hello   readers   this   is   Java  "
Reversed: "Java is this readers Hello"

2. Empty Strings: If you are taking input from the user, you should also check whether the input string is empty or not before passing the string to reverseWords() method. Refer: How to check if string is empty, blank or null.

Place the following code in the beginning of reverseWords() method. This will ensure that when the given string is empty, it returns the string as it is.

// Check if the input string is empty
if (str.isEmpty()) {
return str;
}
❮ Java Tutorial

Top Related Articles:

  1. how to copy one hashmap content to another hashmap
  2. Java String substring() Method with examples
  3. System.getProperty() in java
  4. Java StringBuilder delete()
  5. Convert Comma Separated String to HashSet in Java

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap