Reverse individual words in a string or sentence in Java.

In this context, we are going to learn how to reverse individual words in a string or sentence in Java.
So the user has to Enter the Input

eg: Java is object oriented language so the output will be
avaJ si tcejbo detneiro egaugnal

Java program to reverse individual words in a string or sentence

import java.util.Scanner;
class takString 
{
    public static void main(String[] args) 
    {
    String sentence;
        
    Scanner input = new Scanner(System.in);

  calReverseOfWords cl=new calReverseOfWords();
  
  System.out.println("Enter the sentence ");
  
  sentence=input.next();
  
     cl.implReverseLogic(sentence);
         
    }
}
class calReverseOfWords
{
    void implReverseLogic(String inSentence)
    {
  int i,j;
        String[] sentence = inSentence.split(" ");
         
        String revSentence = "";
         
        for (i = 0; i < sentence.length; i++) 
        {
            String sentence1 = sentence[i];
             
            String revWord = "";
             
            for (j = sentence1.length()-1; j >= 0; j--) 
            {
                revWord = revWord + sentence1.charAt(j);
            }
             
            revSentence = revSentence + revWord + " ";
        }
         
        System.out.println(inSentence);
         
        System.out.println(revSentence);
    }
}

Output:

Java is object oriented language

avaJ si tcejbo detneiro egaugnal

Steps Implemented  to reverse each word of a string

 

1)In this program first we have taken a separate class name calReverseOfWords and inside that, we have declared a method
with one parameter. The method calculates the reverse of each word and prints the result.
2)There is one more class named as takString which contains the main method in this method we are initializing the object of class calReverseOfWords and calling the function (implReverseLogic) using the dot operator and the parameter passed to the function is the input taken by the user.

Also read:

How to reverse a LinkedList in Java

Leave a Reply

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