[Java] How to reverse String in Java?


In java, we can reverse String in java by so many ways as given below:

  1. StringBuffer
  2. StringBuilder
  3. Character Iteration

Reverse String in Java: By StringBuffer

public class ReverseStringExample1 {
public static String reverseString(String str){
StringBuffer sb=new StringBuffer(str);
//String buffer in-built method
sb.reverse();
return sb.toString();
}
}

Reverse String in Java: By StringBuilder

public class ReverseStringExample2 {
public static String reverseString(String str){
StringBuilder sb=new StringBuilder(str);
//String builder in-built method
sb.reverse();
return sb.toString();
}
}

Reverse String in Java: By Character Iteration

public class ReverseStringExample3 {
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
//run loop in reverse order for each character
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i]; //append characters
}
return rev;
}
}

Complete Example: Reverse String In Java

Here consolidated all the ways to reverse String in Java.

public class TestStringInJava {
public static void main(String[] args) {
System.out.println(ReverseStringExample1.reverseString("My Name is Saurabh."));
System.out.println(ReverseStringExample2.reverseString("Facing Issues on IT"));
System.out.println(ReverseStringExample3.reverseString("Learn From Others Experinces"));
}
}
}

Output

.hbaruaS si emaN yM
TI no seussI gnicaF
secnirepxE srehtO morF nraeL

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s