Reverse a string in java

Let’s learn to reverse a string in java.

reverse a string in java

Reverse a string in java

In java, a string can be reversed in ‘n’ number of ways. Let’s learn following ways to reverse a string,

  • using for loop
  • word by word
  • without using function
  • using recursion

Reverse a string in java using for loop

To reverse a string, variable b is iterated through for loop from b = length of the given string to b greater than 0.

Then in the next step character of string is printed at index (a – 1). Lastly print reversed string.

Here’s the program to reverse string using a for loop,

import java.util.Scanner;

public class ReverseStringForLoop 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter a string to reverse: ");
      String strInput = sc.nextLine();    
      System.out.println("Reversed string using for loop '" + strInput + "' is: "); 
      for(int b = strInput.length(); b > 0; --b)
      {
         System.out.print(strInput.charAt(b - 1)); 
      }
      sc.close();
   }
}



Output:

Please enter a string to reverse: helloworld
Reversed string using for loop ‘helloworld’ is: dlrowolleh

Please enter a string to reverse: flowerbrackets
Reversed string using for loop ‘flowerbrackets’ is: stekcarbrewolf


how to reverse a string in java word by word:

Here to reverse string word by word, first read user entered string using nextLine() method of scanner class.

This user entered string is stored in String variable. Then this string variable is converted to character array using toCharArray() method of class String.

Also read – java remove character from string

In the next step two for loops is used. First for loop iterates variable ‘a’ from 0 to a < length of given character array.

Then if chArray[a] != ‘ ‘ add chArray[0] to string strWord. Next until we get space, if block adds characters to string strWord.

Moving on, else block reverses the word if we get space. Lastly second for loop reverses last word.

Here’s how to reverse a string in java word by word,

import java.util.Scanner;

public class ReverseWordByWord 
{
   public static void main(String[] args) 
   {
      String strWord = "";
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter a string: ");
      String strGiven = sc.nextLine();     
      char[] chArray = strGiven.toCharArray();
      System.out.println("Reversed string word by word: ");
      for(int a = 0; a < (chArray.length); a++)
      {
         if(chArray[a] != ' ')
         {
            strWord = strWord + chArray[a];
         }
         else
         {
            for(int b = strWord.length(); b > 0; b--)
            {
               System.out.print(strWord.charAt(b - 1));       
            }
            System.out.print(" ");
            strWord = "";
         }
      }
      for(int b = strWord.length(); b > 0; b--)
      {
         System.out.print(strWord.charAt(b - 1));       
      }
      sc.close();
   }
}



Output:

Please enter a string: hello world java
Reversed string word by word: olleh dlrow avaj

Please enter a string: flower brackets java
Reversed string word by word: rewolf stekcarb avaj


without using reverse function

Let’s see java program,

import java.util.Scanner;

public class ReverseWithoutFunction 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strInput = sc.nextLine();
      int len = strInput.length();
      String strReverse = "";
      System.out.println("Reverse a string without using reverse function: ");
      for(int a = len - 1; a >= 0; a--)
      {
         strReverse = strReverse + strInput.charAt(a);
      }
      System.out.println(strReverse);
      sc.close();
   }
}



Output:

Please enter a string: flowerbrackets
Reverse a string without using reverse function: stekcarbrewolf

Please enter a string: helloworld
Reverse a string without using reverse function: dlrowolleh


using recursion

Recursive function is one which calls itself. Here’s the java program to reverse a string using recursion,

import java.util.Scanner;

public class ReverseUsingRecursion 
{
   String reverseRecursive(String str)
   {
      if(str.length() == 0)
          return " ";
      return str.charAt(str.length() - 1) + reverseRecursive(str.substring(0, str.length() - 1));
   }

   public static void main(String[] args) 
   {
      ReverseUsingRecursion obj = new ReverseUsingRecursion();
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter a string: ");
      String strInput = sc.nextLine();    
      System.out.println("Reverse string using recursion: " + obj.reverseRecursive(strInput));
      sc.close();
   }
}



Output:

Please enter a string: helloworld
Reverse string using recursion: dlrowolleh

Please enter a string: java
Reverse string using recursion: avaj


Reverse a sentence in java

Let’s learn to reverse a sentence in java,

import java.util.Scanner;

public class ReverseSentenceJava 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter a string to reverse a sentence: ");
      String strInput = sc.nextLine();
      String[] strSentence = strInput.split("\s");
      String strReverse = "";
      for(int a = 0; a < strSentence.length; a++) 
      { 
         if(a == strSentence.length - 1)
         {
            strReverse = strSentence[a] + strReverse;
         }
         else
         {
            strReverse = " " + strSentence[a] + strReverse;
         }
      }
      System.out.print("Reverse a sentence in java: " + strReverse);
      sc.close();
   }
}


Output:

Please enter a string to reverse a sentence: hello world core java
Reverse a sentence in java: java core world hello


Reverse a number in java

Now let’s learn to reverse a number in java,

public class ReverseNumberJava
{
   public static void main(String[] args) 
   {
      int number = 5689, reverse = 0;
      System.out.println("Given number: " + number);
      while(number != 0) 
      {
         int digit = number % 10;
         reverse = reverse * 10 + digit;
         number /= 10;
      }
      System.out.println("Reverse number in java: " + reverse);
   }
}


Output:

Given number: 5689
Reverse number in java: 9865


Reverse a string in java using tochararray

In this case first take input from user or read input from user using nextLine() method of Scanner class.

This user input string is stored in String variable ‘strInput’. Here we are using character array to reverse user input string.

In the next step convert string to character array using toCharArray() method. Then get the size of character array using length property.

Now for loop prints characters from last index of character array. Here’s the java program on reverse a string in java using tochararray,

import java.util.Scanner;

public class UsingTochararray 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter a string to reverse: ");
      String strInput = sc.nextLine();    
      char[] chArray = strInput.toCharArray(); 
      System.out.println("Reversed string in java using tochararray: "); 
      int size = chArray.length;
      for(int a = size; a > 0; a--)
      {
         System.out.print(chArray[a - 1]); 
      }
      sc.close();
   }
}


Output:

Please enter a string to reverse: hello world
Reversed string in java using tochararray: dlrow olleh