Friday, September 15, 2023

How to Reverse String in Java with or without StringBuffer Example

Reverse String in Java
There are many ways to reverse a given String in Java. For example, you can use rich Java API to quickly reverse the contents of any String object. Java library provides StringBuffer and StringBuilder class with the reverse() method which can be used to reverse String in Java. Since converting between String and StringBuffer or StringBuilder is very easy it's the easiest way available to reverse String in Java. But, in a coding interview, you may not be allowed to use the JDK API methods to solve this problem. That's why, writing a Java program to reverse String in Java without StringBuffer is one of the popular Java String interview questions, which requires you to reverse String by applying logic and by not using API methods.

Since reverse is a recursive job, you can use recursion as well as a loop to reverse String in Java. In this Java tutorial, you will learn how to reverse String using StringBuffer, StringBuilder, and using a pure loop with logic.

Btw, if you are preparing for coding interviews then a  good knowledge of techniques like Recursion, Dynamic Programming, Greedy Algorithms, and essential data structures like an array, string, linked list, binary tree, stack, queue, etc are very important.

You should put a decent amount of time into brushing these skills before going for any coding interview or taking calls for any telephonic interviews. If you need resources, I recommend Data Structures and Algorithms: Deep Dive Using Java to brush up your Data structure and algorithms skills. This is a great and very affordable course on Udemy which you can buy for just $10 on Udemy sales which happens every now and then. 





Algorithm to Reverse String in Java

Here are the algorithm and codes to reverse a given String in Java without using StringBuffer or any other API methods. The method below shows you how to reverse the String, which you can further reuse to check if the given String is Palindrome or not.

How to Reverse String in Java with or without StringBuffer Example



After initial input validation, we are just iterating through String, starting from end to start and generating a reverse String.

If you want to master the art of solving these kinds of coding problems then Grokking the Coding Interview: Patterns for Coding Questions on Educative is an excellent course to join. This course will teach you how to identify a pattern among different coding problems and use that skill to solve unknown problems that are asked in a coding interview on companies like Google, Amazon, and Microsoft.

How to Reverse String in Java with or without StringBuffer Example



Java Program to Reverse String in Java

Java program to reverse String in Java without StringBuffer or StringBuilderHere is my complete code program to reverse any String in Java. In the main method, we have first used StringBuffer and StringBuilder to reverse the contents of String, and then we wrote our own logic to reverse String.

This uses the toCharArray() method of String class which returns the character array of String. By looping through the character array and appending it into an empty String we can get a reversed String in Java, as shown in the following example.

You can also check How to reverse String with recursion in Java if you want to see the recursive code. let's see the complete Java program for this beautiful Java programming exercise.


/**
 *
 * Java program to reverse String in Java.
 * There are multiple ways to reverse
 * String in Java, you can either take help of standard
 * Java API StringBuffer to reverse String in Java.
 * StringBuffer has a reverse() method which returns StringBuffer
 * with reversed contents. 

 *
 * On the other hand, you can also reverse it by applying your
 * own logic, if asked to reverse String without
 * using StringBuffer in Java. 

 *
 * By the way you can also use StringBuilder to reverse
 * String in Java. StringBuilder is non-thread-safe
 * version of StringBuffer and provides similar API.
 * You can use StringBuilder's reverse()
 * method to reverse content and then convert it back to String
 *
 * @author http://java67.blogspot.com
 */

public class StringReverseExample {
 
 
    public static void main(String args[]) {
     
        //quick wasy to reverse String in Java - Use StringBuffer
        String word = "HelloWorld";
        String reverse = new StringBuffer(word).reverse().toString();
        System.out.printf(" original String : %s ,
               reversed String %s  %n"
, word, reverse);
     
        //another quick to reverse String in Java - use StringBuilder
        word = "WakeUp";
        reverse = new StringBuilder(word).reverse().toString();
        System.out.printf(" original String : %s ,
             reversed String %s %n"
, word, reverse);
     
        // one way to reverse String without using
        // StringBuffer or StringBuilder is writing
        // own utility method
        word = "Band";
        reverse = reverse(word);
        System.out.printf(" original String : %s ,
                            reversed String %s %n"
,
                               word, reverse);
    }  
 
 
    public static String reverse(String source){
        if(source == null || source.isEmpty()){
            return source;
        }      
        String reverse = "";
        for(int i = source.length() -1; i>=0; i--){
            reverse = reverse + source.charAt(i);
        }
     
        return reverse;
    }
   
}

Output:
original String: HelloWorld, reversed String dlroWolleH
original String: WakeUp, reversed String pUekaW
original String: Band, reversed String dnaB


That's all on How to reverse String in Java with and without StringBuffer and StringBuilder. Though being a Java programmer I prefer to use a library and suggest anyone use StringBuffer or StringBuilder to reverse String for any production use. Though it's also a good programming exercise and you should practice it before going for any Java programming interview.


Other Coding Problems and Programming articles you may like
  • How to remove an element from the array without using a third-party library (check here)
  • 10 points about array in Java (read here)
  • 10 Free Courses to learn Data Structure and Algorithms (courses)
  • How to find the largest and smallest number in an array in Java (read here)
  • Difference between array and ArrayList in Java (see here)
  • How to loop over an array in Java (read here)
  • 4 ways to sort array in Java (see here)
  • 100+ Data Structure and Algorithms Problems (solved)
  • How to convert Array to String in Java (read here)
  • 6 Best Dynamic Programming Courses for Interviews (courses)
  • How to print array in Java with examples (read here)
  • How to declare and initialize a multi-dimensional array in Java (see here)
  • How to compare two arrays in Java (check here)
  • 10 Books to learn Data Structure and Algorithms (books)
  • How to find two maximum numbers on an integer array in Java (check here)
  • 7 Best Data Structure and Algorithms courses (online courses)

Thanks for reading this article so far. If you like this String based coding Interview question then please share it with your friends and colleagues. If you have any doubt or feedback then please drop a note. 

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data Structure in Java courses on Udemy. It's completely free, and all you need to do is create a free Udemy account to enroll in this course. 

By the way, What is your favorite Java coding exercise? Palindrom, Prime Number, Producer consumer problem , or this one?  Do let me know in comments. 

57 comments:

  1. Indeed it's commonly asked to write a Java program to reverse String in Java without using reverse function and it's not EASY. first of all reverse can have different meaning e.g. reverse word by word or reverse each character, preserving whitespace etc. They may ask you to use recursion to write reverse String function instead of using for loop. Best way is to prepare well with all kinds of String related question.

    ReplyDelete
    Replies
    1. public class ReverseString {

      private static String hello = "Hello World";

      public static void main(String[] args)
      {
      System.out.println(reverseString(hello));
      }

      public static String reverseString(String s) {
      char c[] = s.toCharArray();
      int i = 0, j = c.length - 1;
      while (i < j) {
      char tmp = c[i];
      c[i] = c[j];
      c[j] = tmp;
      i++;
      j--;
      }
      return new String(c);
      }

      Delete
    2. Thanks for your answer dude ...Your answer helped me more than the bloggers answer

      Delete
    3. Perfect Dear, Thanks A lot

      Delete
    4. class reverse2
      {
      public static void main(String args[])
      {
      String name="rishi thakur";
      char[] c=name.toCharArray();
      for(int i=c.length-1;i>=0;i--)
      {
      System.out.print(c[i]);
      }
      System.out.println();
      }
      }

      Delete
    5. But you didn't converted the character array back to string

      Delete
    6. public class Reverse
      {
      public static void main(String[]args)
      {
      String str="hello";
      String rev="";
      for(int i=str.length()-1;i>=0;i--)
      {
      rev=rev+str.charAt(i)
      }
      sopln(rev)
      }
      }


      Delete
    7. cannot find symbol "i", not getting the solution

      Delete
    8. Reverse a string
      String word="Abc_def_ghi";

      O/p:"cba_fed_ihg"

      Can any one solve plz.

      Thanks in advance.

      Delete
    9. This is recursion 😄

      import java.util.*;
      public class Main
      {
      static String reverse(String s, String ans, int l){
      if(l<0)
      return ans;
      ans = ans + s.charAt(l);
      return reverse(s, ans, l-1);
      }

      public static void main(String[] args) {
      String s = "abcdefg";
      String ans = "";
      System.out.println(reverse(s, ans, s.length()-1));
      }
      }

      Delete
    10. Nice one. Thanks for adding value.

      Delete
  2. Another solution:

    public static String reverse(String s) {

    if(s.length() == 1){
    return s;
    }
    else{
    return s.charAt(s.length()-1)+reverse(s.substring(1, s.length()-1))+s.charAt(0);
    }
    }

    ReplyDelete
    Replies
    1. lie i want to reverse the string like swap between the numbers
      like
      input.abcd
      output i want was.ba dc

      Delete
  3. you can find different ways @ http://javacracker.com/different-ways-to-reverse-a-string/

    ReplyDelete
  4. But,the method isEmpty() is undefined for the type String

    ReplyDelete
  5. input= HELLO WORLD
    output= OLLEH DLROW

    how will get this output without using any inbuild function??
    plz provide me solusn

    ReplyDelete
    Replies
    1. you can split the string in two strings via locating the space, then reverse them and output

      Delete
    2. String S= "Hello World";
      String[] SP = S.split(" ");


      for(int i=SP.length-1;i>=0;i--){
      System.out.println(SP[i]);
      }
      }

      Delete
    3. Above code will throw java.lang.StringIndexOutOfBoundsException
      if the number of characters in the string is even.
      Although it will work perfectly in case of odd number of characters.

      Delete
    4. It won't cause any null pointer exception.

      Delete
  6. why you making people fools you, haven't uses the reverse method at all.......,because if you comment the whole reverse method defined below still you are going to get the
    answer

    ReplyDelete
  7. int length=as.length();
    String reverse="";
    for ( int i = length - 1 ; i >= 0 ; i-- )
    reverse = reverse + as.charAt(i);
    result.setText(reverse);

    ReplyDelete
    Replies
    1. **Cannot invoke setText(String) on the primitive type int



      what should I do?

      Delete
  8. public class REVERSE {
    String abc = "Hello World i should be reversed";
    void reverse(){
    char[] rev =abc.toCharArray();
    for(int i =abc.length()-1 ;i>=0;i--){
    System.out.print(rev[i]);
    }
    System.out.println("\n");
    }
    void wordrevese() {
    String [] Tok = abc.split(" ");

    for(int k = Tok.length-1 ;k>=0;k--){
    System.out.print(Tok[k]+" ");
    }

    }


    public static void main(String[] args){
    REVERSE RV = new REVERSE();
    RV.reverse();
    RV.wordrevese();
    }


    }

    ReplyDelete
  9. Using reverse very easy for us...

    public static void main(String[] args) {
    System.out.println("Enter the String...");
    Scanner scan=new Scanner(System.in);
    String x = scan.next();
    StringBuffer sb=new StringBuffer(x);
    System.out.println(sb.reverse());

    }

    ReplyDelete
  10. Another Program:

    public class ReverseString {
    public String reverseString(String str) {

    if (str.length() == 1) {
    return str;
    }
    String reverse="";

    reverse += str.charAt(str.length() - 1)
    + reverseString(str.substring(0, str.length() - 1));
    return reverse;
    }
    public static void main(String a[]) {
    ReverseString srr = new ReverseString();
    System.out.println("Result: " + srr.reverseString("Java Programming"));
    }

    }

    ReplyDelete
  11. how about
    input:dear god
    output:god dear

    ReplyDelete
    Replies
    1. String S= "dear god";
      String[] SP = S.split(" ");
      for(int i=SP.length-1;i>=0;i--){
      System.out.print(SP[i]+" ");
      }

      Delete
  12. why we write like this String reverse="";why it shows error i can write String reverse;

    ReplyDelete
    Replies
    1. @Arun, there you are initializing String variable reverse with empty String.

      Delete
  13. how to find String both i.e.Reverse and Palindrome

    ReplyDelete
    Replies
    1. @Avinash, if you want to check if String is palindrome or not using recursion then check this solution

      Delete
  14. class mainclass1
    {
    public static void main(String[] args)
    {
    System.out.println("program started");
    String str="sun rises in the east";
    char[] arr=str.toCharArray();
    for (int i=arr.length-1;i>=0 ; i--)
    {
    System.out.print(arr[i]);
    }
    }
    }

    ReplyDelete
  15. is this acceptable?

    Scanner in = new Scanner(System.in);
    System.out.print("Enter String: ");
    input = in.nextLine();

    //string input converting to array each letter
    char inputArr[] = input.toCharArray();

    System.out.print("Original String: "+ input + "\nReversed String: ")
    //displaying the reverse state of the string
    for(int i = input.length(); i > 0 ;--i)
    {
    System.out.print(inputArr[i-1]);
    }

    ReplyDelete
  16. //TODO: Reverse of String
    public class ReverseString {
    //Without using stringBuffer
    public static void StringReverse(String str){
    String rev="";
    String rev2="";
    String rev3="";
    System.out.println("#########BY USING STRING CLASS##########\n");
    /*TODO: Method 1 : a) Covert the String toCharArray it returns the array character..
    * b) Then concatenate them
    */
    System.out.println("######BY USING METHOD 1#######");
    char chararra[]= str.toCharArray();
    for(int i=chararra.length - 1;i>=0;i--){
    rev= rev + chararra[i];
    }

    System.out.println("Result From method 1: "+rev);
    /*TODO: Method 2 : a) Split The String into tokens and,
    * b) Then concatenate them
    */
    System.out.println("######BY USING METHOD 2#######");
    String tokens[]= str.split("");
    for(int i=tokens.length-1;i >= 0;i--){
    rev2 = rev2+tokens[i];
    }
    System.out.println("Result From method 2: "+rev2);

    /*TODO: Method 3 : a) calculate the length of string and use charAt(),
    * b) Then concatenate them
    */
    System.out.println("######BY USING METHOD 3#######");
    int length= str.length();
    for(int i=length-1;i>=0;i--){
    rev3 = rev3+str.charAt(i);
    }

    System.out.println("Result From method 3: "+rev3);

    }
    //TODO: By Using StringBuffer..
    public static void StringBuffer(String str){
    StringBuffer stringbuff = new StringBuffer(str);
    System.out.println();
    System.out.println("########## BY USING STRINGBFFER CLASS#######");
    System.out.println("\nReverse of String By Using reverse method: "+stringbuff.reverse());
    }
    }

    ReplyDelete
  17. //Reverse of String By Using String Class and StringBuffer Class
    public class ReverseString {
    //Without using stringBuffer
    public static void StringReverse(String str){
    String rev="";
    String rev2="";
    String rev3="";
    System.out.println("#########BY USING STRING CLASS##########\n");
    /*TODO: Method 1 : a) Covert the String toCharArray it returns the array character..
    * b) Then concatenate them
    */
    System.out.println("######BY USING METHOD 1#######");
    char chararra[]= str.toCharArray();
    for(int i=chararra.length - 1;i>=0;i--){
    rev= rev + chararra[i];
    }

    System.out.println("Result From method 1: "+rev);
    /*TODO: Method 2 : a) Split The String into tokens and,
    * b) Then concatenate them
    */
    System.out.println("######BY USING METHOD 2#######");
    String tokens[]= str.split("");
    for(int i=tokens.length-1;i >= 0;i--){
    rev2 = rev2+tokens[i];
    }
    System.out.println("Result From method 2: "+rev2);

    /*TODO: Method 3 : a) calculate the length of string and use charAt(),
    * b) Then concatenate them
    */
    System.out.println("######BY USING METHOD 3#######");
    int length= str.length();
    for(int i=length-1;i>=0;i--){
    rev3 = rev3+str.charAt(i);
    }

    System.out.println("Result From method 3: "+rev3);

    }
    //TODO: By Using StringBuffer..
    public static void StringBuffer(String str){
    StringBuffer stringbuff = new StringBuffer(str);
    System.out.println();
    System.out.println("########## BY USING STRINGBFFER CLASS#######");
    System.out.println("\nReverse of String By Using reverse method: "+stringbuff.reverse());
    }
    }

    ReplyDelete
    Replies
    1. Hello Zakir, thank for solution but can you also explain the key advantages, algorithm, big O complexity and how it is better from original solution?

      Delete
  18. How to reverse this string "what about you" to "you about what"

    ReplyDelete
    Replies
    1. @Pyrathyusha, that's called reversing order of words in String, you can check my solution here

      Delete
  19. Reverse string without using any library function.

    ReplyDelete
    Replies
    1. @Abhishek, check out the below answer by @Asad, if you wan to learn more you can also see here

      Delete
  20. reverse a string with
    out using library function is here,,,,
    import java.lang.String;
    public class MainPagalHoon {
    public static void main(String[] args) {
    String words[]={"tum","kon","piyaa","ye","main","hoon"};

    String reverse= "";
    int length=words.length;
    for(int i=0;i=0;j--)
    {
    reverse=reverse+word.charAt(j);
    }
    reverse=reverse+" ";
    }
    System.out.println(reverse);

    }

    }

    ReplyDelete
    Replies
    1. @Asad, good job, can you convert this algorithm to recursive one as well?

      Delete
  21. Is this too simple?

    //---------------
    public static String reversemystring(String mystring) {
    String myreversestring = "";
    for (int i = 0; i <= mystring.length() -1 ; i++) {
    myreversestring = mystring.charAt(i) + myreversestring;
    }
    return myreversestring;
    }
    //-------------

    System.out.println(reversemystring(yourstringtoreverse));

    ReplyDelete
    Replies
    1. @Anonymous, good solution but it is actually using StringBuilder internally. The String concatenation using + operator internally uses StringBuffer or StringBuilder depending upon whether you are running on Java 1.5 or prior version.

      Delete
  22. This my solution. I think this one is efficient. Please let me know.


    public static void main(String[] args)
    {
    String s = "abcdcba";
    int half = s.length()/2,count=0;
    for(int i=0,j=s.length()-1;i<half;i++,j--)
    {
    if(s.charAt(i) == s.charAt(j))
    {
    count++;
    }
    }
    if(count == half)
    {
    System.out.println("String is palindrome");
    }
    else
    {
    System.out.println("String is not a palindrome");
    }
    }

    ReplyDelete
    Replies
    1. Hello Sushil, good solution. But, Can you explain why it is more efficient and will it work for null, empty String or String with both even and odd length?

      Delete
  23. private static String reverse(String s) {
    if (s.length() == 0) {
    return s;
    }
    return reverse(s.substring(1)) + s.charAt(0);
    }

    ReplyDelete
  24. i want code for
    If case_option = 1, Reversal of words with retaining position’s Case
    i.e. If the original sentence is “Wipro TechNologies BangaLore”,
    the new reversed sentence should be “Orpiw SeigOlonhcet ErolaGnab”
    Note that positions 1, 7, 11, 20 and 25 in the original string are uppercase W, T and B.
    Similarly positions 1, 7, 11, 20 and 25 in the new string are uppercase O, S, O, E and G

    ReplyDelete
  25. You should be using StringBuilder inside the reverse method... the way you're doing it is very costly if the String is long (you create a new String every iteration). If the point of your demonstration was to avoid using StringBuilder, then you should be using a char array.

    ReplyDelete
  26. public class string {
    public static void main(String args[])
    {
    String s="Gaurav";
    char a[]=s.toCharArray();
    System.out.println(s.length());
    for(int i=s.length()-1;i>=0;i--)
    {
    System.out.print(a[i]);
    }

    }


    }

    ReplyDelete
  27. class nit1{
    public static void main(String [] args)
    {
    // String input = "AAABBB CCCDDD EEEFFF" ;
    //String input = "ZYXWVUTSRQPONMLKJIHGFEDCBA" ;
    String input = "1234567890" ;

    String s[]=input.split(" ");
    //System.out.println(s[2]);
    for(int i=0;i=0;j--)
    {
    System.out.print(n[j]);
    }
    System.out.print(" ");
    }
    }
    }

    ReplyDelete
  28. import java.util.*;
    class RevString{
    public static void main(String []args){
    System.out.println("Enter a string");
    Scanner sc=new Scanner(System.in);
    String original=sc.next();
    char []c=original.toCharArray();
    for(int i=c.length-1;i>=0;i--){
    System.out.print(c[i]);
    }
    }
    }

    ReplyDelete
  29. import java.util.*;
    public class MyClass {
    public static void main(String args[]) {
    Scanner o=new Scanner(System.in);
    String s=o.nextLine();
    String v="";
    int a=s.length();
    for(int i=a-1;i>=0;i--)
    v=v+s.charAt(i);
    System.out.println(v);
    }
    }

    ReplyDelete
  30. public static void main(String[] args) {
    String str = "abcd";
    reverse(str,0);

    }
    public static String reverseString = "";
    public static void reverse(String str, int idx){
    if(idx == str.length()){
    System.out.println("reverse string : "+ reverseString );
    return;
    }
    char chatAt = str.charAt(idx);
    reverseString = chatAt + reverseString;
    reverse(str, idx+1);
    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.