Reverse a String in Java

Hello,
Here we will see how to reverse a String Java ?
We will see 4 different ways we can reverse a String in Java. Let's go one by one.

1) Using StringBuilder's reverse() method.

This is very simple. All we need to do is create the StringBuilder object using String which we want to reverse and then call reverse() method of StringBuilder using its object.
After that convert the StringBuilder object to String. That's it.

package com.infybuzz.string;

public class StringReverse1 {

 public static void main(String[] args) {
  
  String str = "http://www.infybuzz.com";
  
  StringBuilder stringBuilder = new StringBuilder(str);
  
  stringBuilder.reverse();
  
  System.out.println(stringBuilder.toString());
  
 }

}

Output

moc.zzubyfni.www//:ptth


2) Using byte Array.

Here first we need to convert String into byte[] by calling getBytes() mehtod of String. After that we will do for loop from last element of byte[] and will put into another byte[].

package com.infybuzz.string;

public class StringReverse2 {

 public static void main(String[] args) {
  
  String str = "http://www.infybuzz.com";
  
  byte[] byteArray = str.getBytes();
  
  byte[] resultByteArray = new byte[byteArray.length];
  
  int count = 0;
  
  for(int i = byteArray.length - 1 ; i >= 0 ; i--) {
   resultByteArray[count] = byteArray[i];
   count++;
  }
  
  System.out.println(new String(resultByteArray));
  
 }

}

Output

moc.zzubyfni.www//:ptth


3) Using char Array.

Here first we need to convert String into char[] by calling toCharArray() mehtod of String. After that we will do for loop from last element of char[] and will put into another char[].

package com.infybuzz.string;

public class StringReverse3 {

 public static void main(String[] args) {
  
  String str = "http://www.infybuzz.com";
  
  char[] charArray = str.toCharArray();
  
  char[] resultCharArray = new char[charArray.length];
  
  int count = 0;
  
  for(int i = charArray.length - 1 ; i >= 0 ; i--) {
   resultCharArray[count] = charArray[i];
   count++;
  }
  
  System.out.println(new String(resultCharArray));
  
 }

}

Output

moc.zzubyfni.www//:ptth


4) Using reverse() method of Collections ?

Here first we need to convert String into char[] by calling toCharArray() mehtod of String. After that we will put all elements of char[] into ArrayList of type Character. And then need to call reverse() method of Collections.

package com.infybuzz.string;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StringReverse4 {

 public static void main(String[] args) {
  
  String str = "http://www.infybuzz.com";
  
  char[] charArray = str.toCharArray();
  
  List<Character> charList = new ArrayList<Character>();
  
  
  for(char c : charArray){
   charList.add(c);
  }
  
  Collections.reverse(charList);
  
  for(char c : charList){
   System.out.print(c);
  }
  
 }

}

Output

moc.zzubyfni.www//:ptth