Java Program To Reverse A String


Write a java program to reverse a string?

This is one of the most frequently asked java program in the technical round of java fresher’s interview. Interviewer may ask you to write different ways to reverse a string or he may ask you to reverse a string without using in-built methods or he may ask you to reverse a string using recursion.

In this post, I have discussed 3 different ways to reverse a string.

1) Using StringBuffer class

In this method, we use reverse() method of StringBuffer class to reverse the string. Here is the code snippet to reverse the string using reverse() method of StringBuffer class.

StringBuffer sbf = new StringBuffer("MyJava");

System.out.println(sbf.reverse());    //Output : avaJyM

2) Using iterative method

In this method, first we convert given string to char array using charArray() method. And then we iterate that array in the reverse order.

String str = "MyJava";

char[] strArray = str.toCharArray();

for (int i = strArray.length - 1; i >= 0; i--)
{
	System.out.print(strArray[i]);     //Output : avaJyM
}

3) Using recursive method.

Here is the method which reverses the string by calling itself recursively.

static String recursiveMethod(String str)
{
	 if ((null == str) || (str.length() <= 1))
	 {
	        return str;
	 }

	 return recursiveMethod(str.substring(1)) + str.charAt(0);
}

This method takes the first character of a string (str.charAt(0)) and puts it at the end of the string. And then calls itself on the remainder of the string (str.substring(1)). Finally adds these two things to get the reverse of the passed string (recursiveMethod(str.substring(1)) + str.charAt(0)). When the passed string is one character or less (str.length() <= 1), it stops calling itself and just returns the string passed.

If the “MyJava” is the string to reverse, then this method works like this.

1st Call —>   recursiveMethod(“MyJava”)
2nd Call —> recursiveMethod(“yJava”) + “M”
3rd Call —>  (recursiveMethod(“Java”) + “y”) + “M”
4th call —>  ((recursiveMethod(“ava”) + “J”)+”y”) + “M”
5th Call —>  (((recursiveMethod(“va”) + “a”) + “J”)+”y”) + “M”
6th Call —>  ((((recursiveMethod(“a”) + “v”) + “a”) + “J”)+”y”) + “M”

After 6th call, it Stops calling itself. Because the length of passed string is 1. So, finally it returns “avaJyM”.

Below is the Java program which reverses the string “MyJava” using all three above methods.

public class ReverseTheString
{
	public static void main(String[] args)
	{
		String str = "MyJava";

		//1. Using StringBuffer Class

		StringBuffer sbf = new StringBuffer(str);

		System.out.println(sbf.reverse());    //Output : avaJyM

		//2. Using iterative method

		char[] strArray = str.toCharArray();

		for (int i = strArray.length - 1; i >= 0; i--)
		{
			System.out.print(strArray[i]);    //Output : avaJyM
		}

		System.out.println();

		//3. Using Recursive Method

		System.out.println(recursiveMethod(str));    //Output : avaJyM
	}

	//Recursive method to reverse string

	static String recursiveMethod(String str)
	{
		 if ((null == str) || (str.length() <= 1))
		 {
		        return str;
		 }

		 return recursiveMethod(str.substring(1)) + str.charAt(0);
    }
}

53 Comments

  1. sir i want a program to reverse words in a sentence “This is Java class” o/p— ssalc avaJ si sihT pls anyone try to reply by using string/sbuilder/sbuffer…

    • import java.util.Scanner;

      public class Stringrev {

      public static void main(String[] args) {
      String name;
      System.out.println(“Enter a string”);
      Scanner s = new Scanner(System.in);
      name = s.nextLine();
      StringBuffer sb = new StringBuffer(name);

      System.out.println(sb.reverse());
      }

      }

        • @jram

          import java.util.Scanner;
          class WordReverse
          {
          public static void main(String args[])
          {
          Scanner sc=new Scanner(System.in);
          String str=sc.nextLine();
          String[] words=str.split(” “);
          for(int i=words.length-1;i>=0;i–)
          {
          System.out.print(words[i]+” “);
          }
          }
          }

          • import java.util.Scanner;
            class Temp{
            public static void main(String[] args) {
            String str1=””;
            Scanner sc=new Scanner(System.in);
            System.out.println(“Enter a String: “);
            String str=sc.nextLine();
            //StringBuffer strbuf=new StringBuffer(str);
            char[] charr=str.toCharArray();
            for(int i=0;i<=charr.length-1;i++)
            {
            if(i==6)
            {
            for(i=6;i<=charr.length-1;i++)
            {
            System.out.print(charr[i]);
            }
            }
            else
            {
            str1+=charr[i];
            }
            }
            System.out.print(" "+str1);
            }
            }

          • static void stringreverse(){
            String str[] = “i am a java Developer”.split(” “);
            String temp =””;
            for (int i=str.length-1;i>=0;i–){
            temp+= str[i]+” “;
            }
            System.out.println(temp.substring(0,temp.length()-1));
            }
            public static void main(String[] args) {
            stringreverse();
            }

    • program to reverse words in a sentence “This is Java class” o/p— ssalc avaJ si sihT

      private void reverseWords(String line){
      String res = “”;
      String[] tokens = line.split(” “);
      for(int i=tokens.length-1;i>=0;i–)
      res += ” “+reverse(tokens[i]);
      System.out.println(“reverse words:”+res);
      }
      private String reverse(String s){
      if(s!=null && s.length()>=1)
      return reverse(s.substring(1))+s.charAt(0);
      return “”;
      }

      • //Using iterative method
        public String reverseSenctence (String str) {
        StringBuilder builder = new StringBuilder();

        String[] strArray = str.split(” “);

        for (int i = strArray.length-1;i>=0;i–) {
        char[] charArray = strArray[i].toCharArray();

        for (int j = charArray.length-1;j>=0;j–) {
        builder.append(charArray[j]);
        }
        if(i !=0) {
        builder.append(” “);
        }
        }
        return builder.toString();
        }

    • String str= “this is a string”;
      String[] strarray=str.split(“\\s”);
      String revstr=””;
      System.out.println(“input string is:”+ str);
      for(String str1:strarray){ revstr=str1+ ” ” +revstr;}
      System.out.println(“reverse string is: ” +revstr);

  2. One more solution :

    static void otherMethod(String string) {

    char[] charArray = string.toCharArray();
    int start = 0 ;
    int end = charArray.length-1 ;

    while(end > start ){

    char ch = charArray[start];
    charArray[start] = charArray[end];
    charArray[end] = ch ;

    start++;
    end– ;

    }

    System.out.println(new String(charArray).intern());

    }

  3. Why do we need to do the following in the iterative approach?
    char[] strArray = str.toCharArray();

    I think, we can easily skip this step and simply iterate the string from str.length()-1.

  4. public class ReverseTheString
    {
    public static void main(String[] args)
    {
    String str = “MyJava”;

    //1. Using StringBuffer Class

    StringBuffer sbf = new StringBuffer(str);

    System.out.println(sbf.reverse()); //Output : avaJyM

    //2. Using iterative method

    char[] strArray = str.toCharArray();

    for (int i = strArray.length – 1; i >= 0; i–)
    {
    System.out.print(strArray[i]); //Output : avaJyM
    }

    System.out.println();

    //3. Using Recursive Method

    System.out.println(recursiveMethod(str)); //Output : avaJyM
    }

    //Recursive method to reverse string

    static String recursiveMethod(String str)
    {
    if ((null == str) || (str.length() <= 1))
    {
    return str;
    }

    return recursiveMethod(str.substring(1)) + str.charAt(0);
    }
    }

  5. one other way:

    public class StringRecursiveReversal {
    public static void main(String[] args) {
    String s=”MyJava”;
    char ch[]=s.toCharArray();
    int l=ch.length;
    while(l>0){
    System.out.print(ch[l-1]);
    l–;
    }
    }

    }

  6. hi sir why can i do in this problem
    ****** Implement the following method: String reverseHalves(String str) The method will do the following to a String and return it:
    Input: abcXYZ
    Output: XYZcba

    • import java.util.*;
      class Test5{
      public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      System.out.println(“Enter your name :”);
      String str= sc.nextLine();

      String upper=””;
      String lower=””;

      for(int i=0;i=97||str.charAt(i)>=122)
      {
      lower+=str.charAt(i);
      }
      else
      {
      upper+=str.charAt(i);
      }
      }
      for(int j=lower.length()-1;j>=0;j–)
      {
      upper=upper+str.charAt(j);
      }
      System.out.println(upper);

      }
      }

  7. Also we can use this Example with StringBuffer as a part of “reverse number”
    See the below example

    public class ReverseString {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    StringBuffer buffer = new StringBuffer(“12345678”);
    String reverse =buffer.reverse().toString();
    System.out.println(“Reverse String of “+buffer+ ” is “+reverse);
    int num = Integer.parseInt(reverse);
    System.out.println(num);
    }

    }

  8. Hi, I am not able to understand how recursive method is working.
    when we are calling return recursiveMethod(str.substring(1)) + str.charAt(0); it should pass the String by taking 1st char at last. for example

    suppose we passing “SRT” so in 1st iteration return recursiveMethod(str.substring(1)) + str.charAt(0); will pass “RTS” to method recursiveMethod and length still remains 3 when glow start. so after reversing also it will continue reversing as “str” will never become less than 1.

    This is my understanding but i know i am. please correct where i am thinking wrong. Thanks

  9. import java.io.*;
    class Reversetext{
    public static void main(String []args)throws IOException
    {
    System.out.println(“enter the name:”);
    InputStreamReader s=new InputStreamReader(System.in);
    BufferedReader br=new BufferedReader(s);
    String name=br.readLine();
    StringBuffer sb=new StringBuffer();
    sb.append(name);
    System.out.println(sb.reverse());
    }
    }

  10. Hello sir,
    I am getting stackOverFlowError for this code

    static String recursiveMethod(String str)
    {
    if ((null == str) || (str.length() <= 1))
    {
    return str;
    }

    return recursiveMethod(str.substring(1)) + str.charAt(0);
    }
    So What can be the solution??

  11. hey i want to write a program in which given string words will be reversed, anyone can help
    without using any string methods like split

    eg INPUT-HELLO RAM HI
    OUTPUT-HI RAM HELLO

    • String s1 = “HELLO RAM JI”;
      String[] s2 = s1.split(” “);

      for(int i=s2.length()-1; i>=0; i–)
      {
      System.out.print(s2[i]+” “);
      }

  12. Hello, I was happy to find this wonderful website.
    I am wondering if there is a section on control statements and logical operators, IF, ELSE, DO, WHILE, etc.?
    If not, where would you recommend I go?
    Thanks

    • @suneel
      try this

      import java.util.Scanner;
      public class ReverseWordcount
      {
      public static void main(String[] args)
      {
      int[] count=new int[50];
      Scanner sc=new Scanner(System.in);
      String str=sc.nextLine();
      String[] words = str.split(” “);
      String reversedString = “”;
      for (int i = 0; i = 0; j–)
      {
      reverseWord = reverseWord + word.charAt(j);
      count[j]=reverseWord.length();
      }
      System.out.print(reverseWord+count[i]+” “);
      }
      }
      }

    • import java.util.Scanner;
      public class ReverseStringWithCount {
      public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println(“Enter Sentence”);
      String input = sc.nextLine();

      String[] words = input.split(” “);
      for(int i=0;i<words.length;i++){
      String word=words[i];
      StringBuffer Reverse= new StringBuffer(word);
      StringBuffer Reverseword= Reverse.reverse();
      int count=Reverseword.length();
      System.out.print(Reverseword+""+count+" ");

      }
      }

      }

  13. for Reverse string using //2. Using iterative method , we can use charAt() method instead of creating a character array.
    for(int i = s.length()-1;i>=0;i–)
    {
    System.out.print(str.charAt(i));
    }

  14. public static void reverseThisString(String str)
    {
    String[] stringArray=str.split(“”);
    for(int i=stringArray.length-1;i>=0;i–)
    {
    System.out.print(stringArray[i]);
    }
    }

  15. //Write a java program to reverse words in a sentence
    public class ReverseAstringInSentence {
    // Using iterative method
    public String reverseSenctence(String str) {
    StringBuilder builder = new StringBuilder();
    String[] strArray = str.split(” “);
    for (int i = strArray.length – 1; i >= 0; i–) {
    char[] charArray = strArray[i].toCharArray();

    for (int j = charArray.length – 1; j >= 0; j–) {
    builder.append(charArray[j]);
    }
    if (i != 0) {
    builder.append(” “);
    }
    }
    return builder.toString();
    }
    }
    // Test Case
    public class ReverseAstringInSentenceTest {
    private ReverseAstringInSentence reverseAstringInSentence;
    private String input1 = “This is Java class”;
    @Before
    public void setUp() throws Exception {
    reverseAstringInSentence = new ReverseAstringInSentence();
    }
    @Test
    public void testReverseSenctence() {
    String actual = reverseAstringInSentence.reverseSenctence(input1);
    assertEquals(“ssalc avaJ si sihT”, actual);
    }
    }

  16. public static void main(String[] args) {
    String st = “ReverseAString”;
    StringBuilder sb = new StringBuilder();
    for (int i = st.length()-1; i >= 0; i–) {
    sb = sb.append(st.charAt(i));
    }
    System.out.println(sb);
    }

  17. Another way of reversing array using recursion –
    public static String reverseString1(String str) {
    if (str==null || str.length()<=1) {
    return str;
    }
    return str.charAt(str.length()-1)+str.substring(0, str.length()-1);

    }

  18. recursiveMethod(str.substring(1)) + str.charAt(0)
    Plz explain how this method call internally works with + char value? debugging?

  19. public class MainClass {

    public static void main(String[] args) {
    StringBuffer name = new StringBuffer(“Aakash”);
    System.out.println(“Aakash”);
    for (int i = 0; i < name.length()/2; i++) {
    int firstIndex = i;
    int lastIndex = name.length()-i-1;
    char firstChar = name.charAt(firstIndex);
    char lastChar = name.charAt(lastIndex);
    name.setCharAt(lastIndex, firstChar);
    name.setCharAt(firstIndex, lastChar);
    }
    System.out.println(name);
    }
    }

  20. There are there othere methos as well to reverse string

    public static void main (String[] args){
    String str = “Hello World”;
    String rev = “”;

    for(int i =str.length()-1;i>=0; i–){
    rev = rev+ charAt(i);
    }
    System.out.println(rev)
    }

Leave a Reply