All TalkersCode Topics

Follow TalkersCode On Social Media

Reverse Each Word In A String Java

Last Updated : Sep 1, 2023

Reverse Each Word In A String Java

In this article we will show you the solution of reverse each word in a string java, after giving a general description of the approach we'll take, we'll start writing the code.

You will have a thorough understanding of how to reverse each word in a given string at the end of this course, enabling you to use this information in your personal Java projects.

We will use a straightforward and efficient method to reverse every word in a string.

First, we will use the space character as a delimiter to separate the given string into individual words.

Then, for each word, we will traverse from the last character to the first character to invert its characters.

The updated string will then be created by putting together the reversed words.

Step By Step Guide On Reverse Each Word In A String Java :-

package stringclass;
public class SR {
    public static void main(String[] args) {
        String ip="JAVA";
        String op="";
        char c;
        for (int a = 0; a < ip.length(); a++){
            c = ip.charAt(a);
            op = c + op;
        System.out.println("Orignal String: "+ip);
        System.out.println("Reverse String: "+op);
  1. Importing the stringclass package comes first.
  2. We establish a class called SR.
  3. We declare and initialise the string variable ip having its value "JAVA" inside the main procedure. The initial string which we want to invert is this one.
  4. In order to save the reversed string, we define an empty string variable.
  5. A character variable named c is declared.
  6. Using the length() method, we begin a for loop which repeats from 0 to the length that is the ip string.
  7. The charAt() method is used inside the loop to retrieve a character at the present index a and add it into the variable c.
  8. By adding the character c in front of the current value of op, we concatenate it with the op string. The characters' roles are practically reversed as a result.
  9. After the loop, we use System.out.println() to print the original text and combine it into the contents of the ip string.
  10. Using System.out.println(), we print the inverted string and join it into the value that is the op string.

Conclusion :-

This tutorial taught us how to use Java to reverse every word in a string.

We used a step-by-step procedure to separate the string in words, flip each word, and finally put them back together to create the updated string.

You may quickly reverse the words of any particular string by using the provided code.

Applications for this knowledge include handling text, analysis of data, and string manipulation jobs in Java programming, among other situations.

I hope this article on reverse each word in a string java helps you and the steps and method mentioned above are easy to follow and implement.

Latest Tutorials