How to Reverse a String in Java

The Java program reverses a string using different techniques and inbuilt methods which we’ll be discussing in this article.

 

In Java, objects of a String class are immutable, as a results, one can’t alter them. Further, If there is a need to alter a string after its creation, then StringBuilder and StringBuffer are two classes come into picture. As they produce mutable strings and provide reverse() method to reverse a string.

They can be used to finish the program within 2 or 3 lines. Alternatively, a string can also be reversed with the help of an array.

These are the following approaches to reverse a string in Java :

  1. Using StringBuilder
  2. Using StringBuffer
  3. Using toCharArray method
  4. Using swapping technique
  5. Using List
  6. Using recursion technique

Example 1. Program to reverse a string in Java using StringBuilder

Program:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.Scanner;
/**
* Reverse a string using StringBuilder
*
* */
public class StringReverse {
public static void main(String[] args) {
String word;
System.out.print("Please enter a String = ");
Scanner ed = new Scanner(System.in);
word = ed.nextLine();
StringBuilder str = new StringBuilder(word);
System.out.println(word + " reversed to " + str.reverse() + " using in StringBuilder");
}
}
import java.util.Scanner; /** * Reverse a string using StringBuilder * * */ public class StringReverse { public static void main(String[] args) { String word; System.out.print("Please enter a String = "); Scanner ed = new Scanner(System.in); word = ed.nextLine(); StringBuilder str = new StringBuilder(word); System.out.println(word + " reversed to " + str.reverse() + " using in StringBuilder"); } }
import java.util.Scanner;
/**
 * Reverse a string using StringBuilder
 *
 * */
public class StringReverse {

    public static void main(String[] args) {
        String word;
        System.out.print("Please enter a String = ");
        Scanner ed = new Scanner(System.in);
        word = ed.nextLine();
        StringBuilder str = new StringBuilder(word);
        System.out.println(word + " reversed to " + str.reverse() + " using in StringBuilder");
    }
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Please enter a String = Programmerbay
Programmerbay reversed to yabremmargorP using in StringBuilder
Please enter a String = Programmerbay Programmerbay reversed to yabremmargorP using in StringBuilder
Please enter a String = Programmerbay
Programmerbay reversed to yabremmargorP using in StringBuilder

Example 2. Program to reverse a string in Java using StringBuffer

Program:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.Scanner;
/**
* Reverse a string using StringBuffer
*
* */
public class StringReverse {
public static void main(String[] args) {
String word;
System.out.print("Please enter a String = ");
Scanner ed = new Scanner(System.in);
word = ed.nextLine();
StringBuffer str = new StringBuffer(word);
System.out.println(word + " reversed to " + str.reverse() + " using in StringBuffer");
}
}
import java.util.Scanner; /** * Reverse a string using StringBuffer * * */ public class StringReverse { public static void main(String[] args) { String word; System.out.print("Please enter a String = "); Scanner ed = new Scanner(System.in); word = ed.nextLine(); StringBuffer str = new StringBuffer(word); System.out.println(word + " reversed to " + str.reverse() + " using in StringBuffer"); } }
import java.util.Scanner;
/**
 * Reverse a string using StringBuffer
 *
 * */
public class StringReverse {

    public static void main(String[] args) {
        String word;
        System.out.print("Please enter a String = ");
        Scanner ed = new Scanner(System.in);
        word = ed.nextLine();
        StringBuffer str = new StringBuffer(word);
        System.out.println(word + " reversed to " + str.reverse() + " using in StringBuffer");
    }
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Please enter a String = angry
angry reversed to yrgna using in StringBuffer
Please enter a String = angry angry reversed to yrgna using in StringBuffer
Please enter a String = angry
angry reversed to yrgna using in StringBuffer

 

Example 3. Program to reverse a string in Java using char Array

In this approach, we have converted the input string to character array and traversing it backward.

Program:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.Scanner;
/**
* Reverse a string by converting a string to character array
*/
public class StringReverse {
public static void main(String[] args) {
String word, reversed = "";
char ch[];
int i, size;
System.out.print("Please enter a String = ");
Scanner ed = new Scanner(System.in);
word = ed.nextLine();
ch = word.toCharArray();
size = word.length() - 1;
for (i = size; i >= 0; i--) {
reversed = reversed + ch[i];
}
System.out.println(word + " reversed to " + reversed);
}
}
import java.util.Scanner; /** * Reverse a string by converting a string to character array */ public class StringReverse { public static void main(String[] args) { String word, reversed = ""; char ch[]; int i, size; System.out.print("Please enter a String = "); Scanner ed = new Scanner(System.in); word = ed.nextLine(); ch = word.toCharArray(); size = word.length() - 1; for (i = size; i >= 0; i--) { reversed = reversed + ch[i]; } System.out.println(word + " reversed to " + reversed); } }
import java.util.Scanner;

/**
 * Reverse a string by converting a string to character array
 */
public class StringReverse {

    public static void main(String[] args) {
        String word, reversed = "";
        char ch[];
        int i, size;
        System.out.print("Please enter a String = ");
        Scanner ed = new Scanner(System.in);
        word = ed.nextLine();
        ch = word.toCharArray();
        size = word.length() - 1;
        for (i = size; i >= 0; i--) {
            reversed = reversed + ch[i];
        }
        System.out.println(word + " reversed to " + reversed);
    }
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Please enter a String = programmerbay
programmerbay reversed to yabremmargorp
Please enter a String = programmerbay programmerbay reversed to yabremmargorp
Please enter a String = programmerbay
programmerbay reversed to yabremmargorp

Example 4. Program to reverse a string in Java by Swapping

Program:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/**
* Reverse a string by swapping technique
*/
public class StringReverse {
public static void main(String[] args) {
String str = "programmerbay";
char[] chrArr = str.toCharArray();
for (int i = 0 ; i<=str.length() - 1 ;i++){
int backrdPos = str.length() - (i+1);
if(i < (backrdPos) ) {
char temp = chrArr[i];
chrArr[i] = chrArr[backrdPos];
chrArr[backrdPos] = temp;
}
}
System.out.println("Reversed String :: ");
for (char ch:
chrArr) {
System.out.print(ch);
}
}
}
/** * Reverse a string by swapping technique */ public class StringReverse { public static void main(String[] args) { String str = "programmerbay"; char[] chrArr = str.toCharArray(); for (int i = 0 ; i<=str.length() - 1 ;i++){ int backrdPos = str.length() - (i+1); if(i < (backrdPos) ) { char temp = chrArr[i]; chrArr[i] = chrArr[backrdPos]; chrArr[backrdPos] = temp; } } System.out.println("Reversed String :: "); for (char ch: chrArr) { System.out.print(ch); } } }
/**
 * Reverse a string by swapping technique
 */
public class StringReverse {

    public static void main(String[] args) {
        String str = "programmerbay";
        char[] chrArr = str.toCharArray();
        for (int i = 0 ; i<=str.length() - 1 ;i++){
            int backrdPos =  str.length() - (i+1);
            if(i < (backrdPos) ) {
                char temp = chrArr[i];
                chrArr[i] =  chrArr[backrdPos];
                chrArr[backrdPos] = temp;
            }
        }
        System.out.println("Reversed String :: ");
        for (char ch:
             chrArr) {
            System.out.print(ch);
        }
    }
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Reversed String ::
yabremmargorp
Reversed String :: yabremmargorp
Reversed String :: 
yabremmargorp

Example 5. Program to reverse a string in Java using list

Program:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/**
* Reverse a string by converting the string to list
*/
public class StringReverse {
public static void main(String[] args) {
String str = "programmerbay";
List<Character> characterList = new ArrayList<>();
for (char ch:
str.toCharArray()) {
characterList.add(ch);
}
Collections.reverse(characterList);
System.out.print(str+" reversed to :: ");
for (Character ch:
characterList) {
System.out.print(ch);
}
}
}
/** * Reverse a string by converting the string to list */ public class StringReverse { public static void main(String[] args) { String str = "programmerbay"; List<Character> characterList = new ArrayList<>(); for (char ch: str.toCharArray()) { characterList.add(ch); } Collections.reverse(characterList); System.out.print(str+" reversed to :: "); for (Character ch: characterList) { System.out.print(ch); } } }
/**
 * Reverse a string by converting the string to list
 */
public class StringReverse {

    public static void main(String[] args) {
        String str = "programmerbay";
        List<Character> characterList = new ArrayList<>();
        for (char ch:
             str.toCharArray()) {
            characterList.add(ch);
        }
        Collections.reverse(characterList);
        System.out.print(str+" reversed to :: ");
        for (Character ch:
             characterList) {
            System.out.print(ch);
        }
    }
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
programmerbay reversed to :: yabremmargorp
programmerbay reversed to :: yabremmargorp
programmerbay reversed to :: yabremmargorp

Example 6. Program to reverse a string in Java using recursion

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/**
* Reverse a string by recursion
*/
public class StringReverse {
public static void main(String[] args) {
String str = "programmerbay";
System.out.println(str + " reversed to :: "+ getReverseString(str.toCharArray(), str.length() - 1,""));
}
private static String getReverseString(char[] chrArr, int len,String rvrStr) {
if(len < 0){
return rvrStr;
}
rvrStr = rvrStr + chrArr[len];
return getReverseString(chrArr, --len, rvrStr);
}
}
/** * Reverse a string by recursion */ public class StringReverse { public static void main(String[] args) { String str = "programmerbay"; System.out.println(str + " reversed to :: "+ getReverseString(str.toCharArray(), str.length() - 1,"")); } private static String getReverseString(char[] chrArr, int len,String rvrStr) { if(len < 0){ return rvrStr; } rvrStr = rvrStr + chrArr[len]; return getReverseString(chrArr, --len, rvrStr); } }
/**
 * Reverse a string by recursion
 */
public class StringReverse {

    public static void main(String[] args) {
        String str = "programmerbay";
        System.out.println(str + " reversed to :: "+ getReverseString(str.toCharArray(), str.length() - 1,""));
    }

    private static String getReverseString(char[] chrArr, int len,String rvrStr) {
        if(len < 0){
            return rvrStr;
        }
        rvrStr = rvrStr + chrArr[len];
        return getReverseString(chrArr, --len, rvrStr);
    }
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
programmerbay reversed to :: yabremmargorp
programmerbay reversed to :: yabremmargorp
programmerbay reversed to :: yabremmargorp

 

Leave a Reply