17+ Java Programs to Reverse a String

This post contains a total of 17+ Hand-Picked Java Program examples to Reverse a String, with Source Code. All the Programs are made using Java Programming language.

You can use the source code of these programs for educational use with credits to the original owner.

Related Posts

Click a Code to Copy it.

1. By Gaurav Agrawal

Made by Gaurav Agrawal. Java program to reverse a string. Example : Input : qwerty is best Output : tseb si ytrewq. ( Source )


import java.util.*;
public class GauravProgram{
    public static void main(String[] args){
      String scget=(new Scanner(System.in)).nextLine(),q="",f="";
      int l=scget.length(),n=0;
      while(n<l){
          f=scget.substring(n,n+1);
          q=f.concat(q);
          n++;
      }
      System.out.print("\nU have entered :::\n\n"+scget+"\n\n\noutput :::\n\n"+q);
    }
}

2. By 0_O Mägár_Sám_ÄkàNüllpøïntêrÈxëcéptïön

Made by 0_O Mägár_Sám_ÄkàNüllpøïntêrÈxëcéptïön. This java program shows us 20 different ways to reverse a string, from using deque to treeset. ( Source )

import java.util.*;
import java.util.stream.IntStream;
import java.util.regex.Pattern;

//Wednesday, july 1, 2020
//Author magar sam

interface Reverseable
{
    void reverseList();
    void listIterator();
    void stackReverse();
    void reverseSort();
    void deque();
    void treeSet();
    void descendingIterator();
    void descendingSet();
    void swapping();
    void stringBuilder(); 
    void unicodeRLOcharacter();
    void reverseByXor();
    void streams();
    void codePointBefore();
    void forLoops(); 
    void classicalForLoop(); 
    void doWhileLoop();
    void simpleWhileLoop();
    void simpleRecursion();
    void reduce(); //by sushmita banik
    String recursiveReverse(String string);
} 


class Myclass  implements Reverseable
{
    public static int i;
    public static String string="reversable";
    public static String[] stringArray ={"r","e","v","e","r","s","a","b","l","e"};
    public static List<Integer> list=new ArrayList<Integer>();

    @Override
    public void reverseList()
    {
        // TODO: Implement this method
        List<String> reverseList=new ArrayList<String>();

        reverseList.addAll(Arrays.asList(stringArray));

        Collections.reverse(reverseList);

        for (String i:reverseList)
            System.out.print(i);
    }



    @Override
    public void listIterator()
    {
        // TODO: Implement this method
        List<String> list=new ArrayList<String>(Arrays.asList(stringArray));
        ListIterator<String> listiterator=list.listIterator(); 

        for (String i:list)
            listiterator.set(listiterator.next());

        while (listiterator.hasPrevious())
        {
            System.out.print(listiterator.previous());
        }

    }
    
    
    @Override
    public void stackReverse()
    {
        // TODO: Implement this method
        Stack<String> stack=new Stack<String>();

        for (String i:stringArray)
            stack.push(i);

        while (!stack.empty())
        {
            System.out.print(stack.pop());
        }
    }


    @Override
    public void reverseSort()
    {
        // TODO: Implement this method
        Integer [] array=list.toArray(new Integer[list.size()]);
        Integer [] arr= Arrays.copyOfRange(array, 0, string.length());

        Arrays.sort(arr, Collections.reverseOrder()); 

        for (Integer i:arr)
            System.out.print(string.charAt(i));
    }


    @Override
    public void deque()
    {
        // TODO: Implement this method
        String queue;
        Deque<String> list=new LinkedList<String>();

        list.addAll(Arrays.asList(stringArray));

        while (!list.isEmpty())
        {
            queue = list.getLast();
            System.out.print(queue);
            list.removeLast();
        }
    }


    @Override
    public void treeSet()
    {
        // TODO: Implement this method
        TreeSet<Integer> TreeSet=new TreeSet<Integer>(); 
        TreeSet.addAll(list.subList(0, string.length()));


        while (!TreeSet.isEmpty())
        {
            System.out.print(string.charAt(TreeSet.last()));
            TreeSet.remove(TreeSet.last());
        }
    }


    @Override
    public void descendingIterator()
    {
        // TODO: Implement this method
        Integer cout=0;
        TreeSet<Integer> set=new TreeSet<Integer>();
        for (int i=0;i < string.length();i++)
            set.add(i);
        Iterator<Integer> iterator=set.descendingIterator();

        while (iterator.hasNext())
        {
            cout = iterator.next();
            System.out.print((char)string.codePointAt(cout));
        }
    }


    @Override
    public void descendingSet()
    {
        // TODO: Implement this method 
        TreeSet<Integer> TreeSet=new TreeSet<Integer>(); 
        TreeSet.addAll(list.subList(0, string.length()));
        NavigableSet<Integer> NavigavibledescendingSet=TreeSet.descendingSet();

        for (Integer i:NavigavibledescendingSet)
            System.out.print(string.charAt(i));

    }

    @Override
    public void stringBuilder()
    {
        // TODO: Implement this method 
        StringBuilder stringbuilder=new StringBuilder(string); 
        System.out.print(stringbuilder.reverse().toString());
    }
    
    
    @Override
    public void unicodeRLOcharacter()
    {
        // TODO: Implement this method 
        System.out.print("‮" + string);
    }
    
    
    
    @Override
     public void reverseByXor()
     {
        // TODO: Implement this method
        int i=0;
        char [] charArray =string.toCharArray();
        int y=charArray.length-1;
        
           while(i<y){
            charArray[i]=(char) (charArray[i] ^ charArray[y]);
            charArray[y]=(char) (charArray[i] ^ charArray[y]);
            charArray[i]=(char) (charArray[i] ^ charArray[y]);
            i++; y--;
            
         }
        for(Character c:charArray)
            System.out.print(c);    
      }



    @Override
    public void streams()
    {
      // TODO: Implement this method
      char [] temp =string.toCharArray();
      IntStream.range(0,temp.length).
      mapToObj(i -> temp[(temp.length - 1) - i]).
      forEach(System.out::print);
    }
    
    
    @Override
    public void codePointBefore()
    {
     // TODO: Implement this method
    //codePointBefore(int index) will return Unicode code point at the location     that precedes that specified by index 
        System.out.print((char)string.codePointAt(string.length() - 1));

        for (int i=0;i <= string.length() - 2;i++)
         System.out.print((char)string.codePointBefore((string.length() - 1) - i));

    }


    @Override
    public void swapping()
    {
        // TODO: Implement this method 
        for (int i = 0, y = stringArray.length - 1; i < y; i++,
        y--)
        {
            String chars = stringArray[i];
            stringArray[i] = stringArray[y];
            stringArray[y] = chars;
        }

        for (String j:stringArray)
            System.out.print(j);

        //assigning stringArray to it's original forward state 
        for (int i=0;i <= string.length() - 1;i++)
            stringArray[i] = stringArray[(stringArray.length - 1) - i];

    }


    @Override
    public void forLoops()
    {
        // TODO: Implement this method  
        for (int i=0;i <= string.length() - 1;i++)
            System.out.print(string.charAt((string.length() - 1) - i));
    } 
    

    @Override
    public void classicalForLoop()
    {
        // TODO: Implement this method 
        for (int i=string.length() - 1;i >= 0;i--)
            System.out.print(string.charAt(i));
    } 
    

    @Override
    public void doWhileLoop()
    {
        // TODO: Implement this method
        int count=string.length();
        do{
            System.out.print(string.charAt(count -= 1));
        }while(count != 0);
    }


      @Override
       public void simpleWhileLoop()
     {
           // TODO: Implement this method
          int i=string.length();
           while (i != 0)
          {
            System.out.print(string.charAt(i -= 1));
          }
       }


    @Override
    public void simpleRecursion()
    {
        // TODO: Implement this method
        i += 1;
        System.out.print(string.charAt((string.length() - i)));

        if (string.length() == i)
            return ;

        simpleRecursion();
    } 
    
      @Override
    public void reduce()
    {
        // TODO: Implement this method
        
          System.out.print(
            Pattern.compile("").
            splitAsStream(
            string
            ).
            reduce((a, b) -> b + a).
            get()
        );
    }


    @Override
    public String recursiveReverse(String string)
    {
        // TODO: Implement this method 
        if (string.length() == 1)
            return string;

        return recursiveReverse(string.substring(1)) + string.charAt(0);
    } 

}


public class Programe extends Myclass
{
  public static Myclass interfaceFunction;
  public static Integer [] intArray = new Integer[99];
    public static void main(String[] args)
    {
    interfaceFunction = new Programe();
    
    Arrays.setAll(intArray,i -> i);
    
    list.addAll(Arrays.asList(intArray));


      System.out.println("Reverse Item = reverseable");
        printLine();
        printLine("Collection.reverse() method");
        interfaceFunction.reverseList();
        printLine();
        printLine("listIterator");
        interfaceFunction.listIterator();
        printLine();
        printLine("Stack");
        interfaceFunction.stackReverse();
        printLine();
        printLine("Collection.reverseOrder()");
        interfaceFunction.reverseSort();
        printLine();
        printLine("Deque");
        interfaceFunction.deque();
        printLine();
        printLine("TreeSet");
        interfaceFunction.treeSet();
        printLine();
        printLine("descendingIterator");
        interfaceFunction.descendingIterator();
        printLine();
        printLine("descendingSet");
        interfaceFunction.descendingSet();
        printLine();
        printLine("swapping");
        interfaceFunction.swapping();
        printLine();
        printLine("XOR oprator");
        interfaceFunction.reverseByXor();
        printLine();
        printLine("StringBuilder");
        interfaceFunction.stringBuilder();
        printLine();
        printLine("unicodeRLOcharacter");
        interfaceFunction.unicodeRLOcharacter();
        printLine();
        printLine("streams");
        interfaceFunction.streams();
        printLine();
        printLine("codePointBefore() method");
        interfaceFunction.codePointBefore();
        printLine();
        printLine("forLoops");
        interfaceFunction.forLoops();
        printLine();
        printLine("classicalForLoop");
        interfaceFunction.classicalForLoop();
        printLine();
        printLine("doWhileLoops");
        interfaceFunction.doWhileLoop();
        printLine();
        printLine("simpleWhileLoop");
        interfaceFunction.simpleWhileLoop();
        printLine();
        printLine("simpleRecursion");
        interfaceFunction.simpleRecursion();
        printLine();
        printLine("reduce");
        interfaceFunction.reduce();
        printLine();
        printLine("recursiveReverse");
        System.out.print(interfaceFunction.recursiveReverse(string));

    }
    
    public static void printLine(String str)
    {
        System.out.print("String Reverse Using " + str+"=> ");
    }
    
    public static void printLine()
    {
        System.out.println();
    }

}

3. By Ketan

Made by Ketan. ( Source )


import java.util.*;
class Reverse
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
s=s+" ";
int p=0,i,j,n;char ch,ch1;
String rev="";
String rev1="";
int l=s.length();
for(i=0;i<l;i++)
{
ch=s.charAt(i);
if(ch==' ')
{
rev=s.substring(p,i+1);
StringBuffer k=new StringBuffer(rev);
rev1=rev1+k.reverse();
p=i+1;
}
}
System.out.println("Original string="+s);
System.out.println("Reversed string="+rev1);
System.out.println("Thank you for running this code");
}}

4. By Prudhvi Raaj

Made by Prudhvi Raaj. Run the program and enter your string. ( Source )

import java.util.*;
public class Program
   {
 public static void main(String[] args)
    {
  Scanner st= new Scanner(System.in);
  
     String name = st.nextLine();
     
   System.out.println("entered string is\n"+" "+name);
   System.out.println("Reversed string is");
for(int x=(name.length()-1);x>=0;x--)
        {
        System.out.print(name.charAt(x));
        }
    }
}

5. By JΞΜΔ 🇨🇩👑 [ActiveChallenger]

Made by JΞΜΔ 🇨🇩👑 [ActiveChallenger]. ( Source )

/*Reverse string 
input: abcd
output: dcba
*/

import java.util.Scanner ;
public class ReverseString
{
public static void main (String[] args)
{
System.out.println("");
Scanner read = new Scanner (System.in);
String str = read.nextLine();
String reverse = "";
for (int i = str.length() - 1; i >= 0; i-- )
{
reverse = reverse + str.charAt(i);
}
System.out.println("");
System.out.println(reverse);
}
}

6. By AJ

Made by AJ. Java program to reverse a input string. ( Source )

import java.util.*;

public class ReverseString {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       
        String x = sc.nextLine();
        
        System.out.println(x);
        
        int size = x.length();
        
        System.out.println("Length = " + size);
        
        System.out.println();
        System.out.println("-----First Way-----");
        System.out.println();
        
        char[] y = x.toCharArray();
        char[] z = new char[size];
        
        int i = 0;
        
        while(i != size) {
            z[i] = y[size - 1 - i];
            i++;
        }
        
        System.out.println(z);
        
        //2nd way
        
        System.out.println();
        System.out.println("-----Second Way-----");
        System.out.println();
        
        for(int j = 0; j < size; j++) {
            z[j] = x.charAt(size - 1 - j);
        }
        
        System.out.println(z);
    }
}

7. By Nikky Amresh

Made by Nikky Amresh. Enter your input string in line ‘String str=”ohh my god”‘. ( Source )


public class Splitrev{
    public static void main(String args[]){
     String str="ohh my god";
     String[] strs=str.split(" ");
     for(String s:strs){
 String r= new StringBuffer(s).reverse().toString();
     System.out.print(r+" ");
     }
}}

8. By marjel101

Made by marjel101. REVERSE A STRING, using recursion, input: a string, output: the same string, but reversed. ( Source )


import java.util.Scanner;
public class ReverseString
{
	public static void main(String args[])
	{
		System.out.println("STRING REVERSER\nEnter a string to reverse.");
		System.out.println("-----------------------------");
		
		Scanner input = new Scanner(System.in);
		// check if there is a valid input
		if (!input.hasNext()) {
			System.out.println("You forgot to enter a string. Please try again.");
			return;
		}
		String s1 = input.nextLine();
		System.out.println("The string you entered:\n\t" + s1);
		String newS = "";
		newS = reverse(s1, newS);
		System.out.println("The reversed string:\n\t" + newS);
		System.out.println("-----------------------------");
		}
	// recursive method returns the reversed string
	static String reverse(String s1, String newS) {
		newS = s1.substring(0,1) + newS;
		s1 = s1.substring(1);
		if (s1.length() <= 0) {
			return newS;
		} else return reverse(s1, newS);
	}
}

9. By Tapabrata Banerjee

Made by Tapabrata Banerjee. ( Source )



import java.util.Scanner;
public class Program
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter String: ");
        String rev = "", str = sc.next();
        for (int i = str.length() - 1; i>=0; i--)
        {
            rev += str.charAt(i);
        }
        System.out.println("Reversed word: " + rev);
    }
}

10. By Aaron Stone

Made by Aaron Stone. Reverse a Text String using StringTokenizer. ( Source )



import java.util.*;
public class Program
{
    public static void main(String[] args) {
    
        Scanner Scan = new Scanner(System.in);
        String inp = Scan.nextLine();
        
        System.out.println("Input String : "+inp+"\n");
        
        StringTokenizer sT = new StringTokenizer(inp);
        
        int count = sT.countTokens();
        
        String revString = "";
        for(int i = 0; i < count; i++)
        {
        String rip = sT.nextToken();
        revString = rip + " " + revString;
        }
        
        System.out.println("Reversed String : "+revString);
        
    }
}

11. By Lam Wei Li

Made by Lam Wei Li. ( Source )

import java.util.Scanner;

public class Program
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        char[] arr = text.toCharArray();
        
        //your code goes here
        String rev = "";
        for (char i : arr)
            rev = i + rev;
        System.out.println(rev);
    }
}

12. By Sololearn

Made by Sololearn. Java program to reverse a string, made using recursion. ( Source )

public class ReverseString 
{
    public static void main(String[] args)
    {
        String text = "Working with Strings";
        System.out.print(reverse(text));
    }

    public static String reverse(String s) 
    {
        if (s.length() <= 1) 
        {
            return s;
        }
        return reverse(s.substring(1, s.length())) + s.charAt(0);
    }
}

13. By Andrew Gendy

Made by Andrew Gendy. Simple code to reverse a string. ( Source )

import java.util.Scanner;

public class ReversingTheStringByAndrew
{
	public static void main(String[] args) {

// getting input from user
Scanner word = new Scanner(System.in);
// saving input into s
String s = word.nextLine();
// initializing rev string
String rev = "";
System.out.println("Word input by User is: " + s);

// loop to put every char in the string from right to left into the rev string

for (int i = s.length()-1; i>= 0; i--){
rev += s.charAt(i);
}

System.out.println("The Reversed Word is: " + rev);
	}
}

14. By Narges Rajabi

Made by Narges Rajabi. ( Source )

import java.util.*;
 
class ReverseString
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter a string to reverse");
      original = in.nextLine();
 
      int length = original.length();
 
      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);
 
      System.out.println("Reverse of entered string is: "+reverse);
   }
}

15. By Anjali Bisht

Made by Anjali Bisht. Java Code to reverse a string using split method. ( Source )

import java.util.Scanner;

public class ReverseSplit { 
public static void main(String[] args) { 
 String str;
 Scanner in = new Scanner(System.in);
 System.out.println("Enter the String");
 str = in.nextLine();
 String[] rev = str.split(""); //used split method to print in reverse order
 System.out.println("value of rev string :");
 for(int i=0; i<=rev.length-1; i++) {
     System.out.print(rev[i] + "");
 }
 System.out.println();
 
 System.out.println("Value of reverse string");
  for(int i=rev.length-1; i>=0; i--) { 
  System.out.print(rev[i] + ""); 
  }
 }//main
} //class

16. By DLPH

Made by DLPH. Java program to Reverse a String. ( Source )


import java.util.*;
 
class ReverseString
 
{
    public static void main(String args[]){
        String str;
        String rStr;
        Scanner bf=new Scanner(System.in);
        str=bf.nextLine();
 
         
        //Reversing String
        rStr="";
        for(int loop=str.length()-1; loop>=0; loop--)
            rStr= rStr + str.charAt(loop);
         
        System.out.println("Reversed string is: " + rStr);
    }
}

17. By Luis García

Made by Luis García. ( Source )

import java.util.Scanner;

public class ReversedStringDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String text = sc.nextLine();
        System.out.println(reverse(text));
    }

    public static String reverse(String input) {
        char[] arr = new char[input.length()];
        char[] arr2 = input.toCharArray();
        int i = input.length() - 1;

        for (int j = 0; i >= 0 && j < input.length(); i--, j++) {
            arr[i] = arr2[j];
        }

        return String.copyValueOf(arr);
    }
}

18. By Moni

Made by Moni. ( Source )

import java.util.*;
public class Program
{
	public static void main(String[] args) 
	{
		String s1, s2="";
		char ch;
		int l,i;
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter a sentence");
		s1=sc.nextLine();
		l=s1.length();
		for(i=l-1;i>=0;i--)
		{
		    ch=s1.charAt(i);
		    s2=s2+ch;
		}
		System.out.println("Reverse - "+s2);
	}
}