How To Reverse A String In Java

How To Reverse A String In Java | There are many string operations in Java, and reversing a given string is one of them. The reverse of a sentence is a sentence in reverse order i.e. the last character to the first character. In Java, there are many ways to perform reverse operations.

After reversing the String the first character will come last and the last character will come in the first place and so on. Let us see some examples of the reverse of a string. 

Example-1:-
String:- “Know Program”
After reverse, String = “margorP wonK”

Example-2:-
String:- “Welcome to KnowProgram”
String after reverse:- “margorPwonK ot emocleW”

How To Reverse a String In Java Using reverse() Function

Similar to the String class, the StringBuilder class also contains lots of pre-defined methods to perform different operations on the string data types. In the StringBuilder class, the reverse() method is defined to reverse a given String.

  • Method prototype:- public StringBuilder reverse()
  • Return type:- StringBuilder
public class Main {
   public static void main(String[] args) {
      StringBuilder string = new StringBuilder("Know Program");
      System.out.println("String: " + string);
      System.out.println("String after reverse: " 
                         + string.reverse());
   }
}

Output:-

String: Know Program
String after reverse: margorP wonK

The above code works as follows:- First, we define the Main class, and then we use the main method to develop the logic. We instantiate the StringBuilder class using the new keyword.  StringBuilder takes a parameter in that we pass a string to be reversed. After that, we printed the given string. Later by using the reverse() function available in the StringBuilder class we reverse a given string.

Since the reverse() method is available in the StringBuilder class therefore it must be called on the StringBuilder object. If we are working with String values then first we need to convert them into the StringBuilder type object, find the reverse, and again convert back to String. The code snippet for this can be written as follows:-

Java Program To Reverse A String

public class Main {
   public static void main(String[] args) {
      String string = "Hello World";

      // create StringBuilder object by using String
      StringBuilder sb = new StringBuilder(string);

      // find reverse
      sb.reverse();

      // convert StringBuilder to String
      String reverse = sb.toString();

      // display both string
      System.out.println("String: " + string);
      System.out.println("String after reverse: " + reverse);
   }
}

Output:-

String: Hello World
String after reverse: dlroW olleH

Reverse a String In Java Using Recursion

Now let us see how to reverse a string in Java using recursion. Recursion is a process that calls the same process again and again.

Java Program to Reverse a String Using Recursion

public class Main {

   public static void reverseString(String string) {
      if ((string == null) || (string.length() <= 1))
         System.out.println(string);
      else {
         System.out.print(string.charAt(string.length() - 1));
         reverseString(string.substring(0, string.length() - 1));
      }
   }

   public static void main(String[] args) {
      String string = "Welcome to KnowProgram";
      System.out.println("String: " + string);
      System.out.print("String after reverse: ");
      reverseString(string);
   }
}

We have defined a public class named Main, then define a ReverseString() method which uses the recursion technique to display the reverse of a string in Java. In this method, first, we check for a string length. If the string length is 0 or less then we just print the string, or else we reverse a string and print the same.

For recursive calls internally it is using substring() method and removes the last character from the input string. In the main method, we take a string and call reverseString() method recursively to reverse a string.

Output:-

String: Welcome to KnowProgram
String after reverse: margorPwonK ot emocleW

Reverse Words In A String Java

Till now we have developed a Java program to reverse a string i.e. we were treating them as a single word. But now we write a program to reverse words in Java. The words in a sentence are separated by space. Here, we reverse each word in a string using the StringBuilder class.

Example:-
Words = “Hi, How are you?”
Reverse of Words = “,iH woH era ?uoy”

Java Program To Reverse Each Word In String

public class Main {
   public static String reverseWords(String string) {
      String words[] = string.split("\\s");
      String reverse = "";
      for (String word : words) {
         StringBuilder sb = new StringBuilder(word);
         sb.reverse();
         reverse += sb.toString() + " ";
      }
      return reverse.trim();
   }

   public static void main(String[] args) {
      System.out.println(reverseWords("Java Programming Language"));
   }
}

Output:-

avaJ gnimmargorP egaugnaL

We have defined a class Main, In that, we define a static method reverseWords() and in for loop we use StringBuilder class to reverse a string. 

In the reverseWords() method first we split the words based on “\\s” (whitespace) using the string class split() method and stored them in the String array. We have initialized a “reverse” variable of String type to store the results.

After that, we iterated the string array, fetched each word, reversed them using the reverse() method of the StringBuilder class, and concatenated them to the reverse string. Finally, we get the reverse of words.

Reverse a Sentence In Java

Previously we developed a program to reverse words in a string Java where each word was reversed. But while reversing a sentence each word will not be reversed instead their index position will be changed. The reverse of a sentence is a sentence in reverse order without reversing each word. 

Example:-
Sentence= “Hi, How are you?”
The reverse of Sentence= “you? are How Hi,”

Program to Reverse a Sentence In Java

import java.util.Scanner;

public class Main {
   public static void main(String args[]) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a sentence: ");
      String sentence = scan.nextLine();
      String reverse = reverse(sentence);
      System.out.println("Reversed sentence: ");
      System.out.println(reverse);
      scan.close();
   }

   public static String reverse(String string) {
      int i = string.indexOf(" ");
      if (i == -1)
         return string;
      return reverse(string.substring(i + 1)) 
            + " " + string.substring(0, i);
   }
}

Output:

Enter a sentence:
I am learning Java programming language.
Reversed sentence:
language. programming Java learning am I

In this example, we took input from the end user. For this purpose, we imported the Scanner class, created its object, called nextLine() to read the line, and stored the result in a string-type variable. On this variable reverse() method is called.

The reverse() method is a recursive method that calls itself. It takes a string as an input value and returns the string value. In this method, first, we fetched the index of whitespace, if is it not available i.e. string doesn’t contain whitespace then return the string. Else call the reverse() function by passing concatenation of the last word & remaining sentence.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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