Reverse a string in java

Let’s learn to reverse a string in java.

Reverse a string in java

Let’s learn following ways to reverse a string.

reverse a string in java

As we know that String is immutable. String class do not have reverse() method. While StringBuffer class has reverse() method.

First let’s learn to reverse a string using ByteArray.

class ReverseStringByteArray
{
   public static void main(String[] args)
   {
      String input = "HelloWorld";
      // getBytes() method to convert string into bytes[].
      byte[] strByteArray = input.getBytes();
      byte[] output = new byte[strByteArray.length];
      // store output in reverse order
      for(int a = 0; a < strByteArray.length; a++)
         output[a] = strByteArray[strByteArray.length - a - 1];
      System.out.println(new String(output));
   }
}


Output:

dlroWolleH


using StringBuilder class reverse() method

class ReverseUsingReverseMethod
{
   public static void main(String[] args)
   {
      String str = "Hello world Java";
      StringBuilder sb = new StringBuilder();
      // append string to StringBuilder
      sb.append(str);
      sb = sb.reverse();
      // printing reversed String
      System.out.println(sb);
   }
}


Output:

avaJ dlrow olleH


using character array

class ReverseUsingCharacterArray
{
   public static void main(String[] args)
   {
      String str = "HelloWorldJava";
      char[] ch = str.toCharArray();
      for(int a = ch.length - 1; a >= 0; a--)
         System.out.print(ch[a]);
   }
}


Output:

avaJdlroWolleH


using toCharArray() method

class ReverseUsingToCharArrayMethod
{
   public static void main(String[] args)
   {
      String str = "Hello World Java";
      char[] chTemp = str.toCharArray();
      int left, right = 0;
      right = chTemp.length - 1;
      for(left = 0; left < right ; left++, right--)
      {
         // swap values
         char temp = chTemp[left];
         chTemp[left] = chTemp[right];
         chTemp[right]=temp;
      }
      for(char c : chTemp)
         System.out.print(c);
      System.out.println();
   }
}


Output:

avaJ dlroW olleH


using ArrayList object – Collections.reverse() method

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
class ReverseUsingArrayList
{
   public static void main(String[] args)
   {
      String str = "Hello World Java";
      char[] ch = str.toCharArray();
      List<Character> al = new ArrayList<>();
      for(char c: ch)
         al.add(c);
      Collections.reverse(al);
      ListIterator<Character> li = al.listIterator();
      while(li.hasNext())
         System.out.print(li.next());
   }
}


Output:

avaJ dlroW olleH


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 a string in java using for loop.

import java.util.Scanner;
public class ReverseStringForLoop 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("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.println(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.

Also read – java remove character from string

This user entered string is stored in String variable. Then this string variable is converted to character array using toCharArray() method of class 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.

Also read – continue statement in java

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.println("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.println(strWord.charAt(b - 1));       
            }
            System.out.print(" ");
            strWord = "";
         }
      }
      for(int b = strWord.length(); b > 0; b--)
      {
         System.out.println(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


reverse without using reverse function

Let’s see how to reverse a string without using reverse function.

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 reverse a string in java using recursion.

Here’s an example on 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.println("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 how to reverse a sentence in java or reverse a sentence word by word in java.

import java.util.Scanner;
public class ReverseSentenceJava 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("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.println("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


This is all about reversing a string in java. In this post we discussed few simple ways in reversing a string in java.

Hope this post would be helpful for interview for freshers in java.