Skip to content

Instantly share code, notes, and snippets.

@bikashdaga
Last active March 7, 2022 10:45
Show Gist options
  • Save bikashdaga/8f9006cf56d824a5fbadd4ed25a0fcf1 to your computer and use it in GitHub Desktop.
Save bikashdaga/8f9006cf56d824a5fbadd4ed25a0fcf1 to your computer and use it in GitHub Desktop.
How to Reverse a String in Java
1. Using toCharArray():
public static String reverse(String str)
{
String rev="";
char[] finalarray = str.toCharArray();
for (int i = finalarray.length - 1; i >= 0; i--)
rev+=finalarray[i];
return rev;
}
//Sample Input- "Scaler Academy"
//Sample Output-"ymedacA relacS"
2. using StringBuilder:
public String reverse(String str)
{
StringBuilder obj = new StringBuilder();
//append is inbuilt method to append the data
obj.append(str);
obj.reverse();
return obj.toString();
}
//Sample Input- "Scaler Academy"
//Sample Output-"ymedacA relacS"
3. StringBuffer class
StringBuffer sbf = new StringBuffer("MyJava");
System.out.println(sbf.reverse()); //Output : avaJyM
4. iterative method
String str = "MyJava";
char[] strArray = str.toCharArray();
for (int i = strArray.length - 1; i >= 0; i--)
{
System.out.print(strArray[i]); //Output : avaJyM
}
@bikashdaga
Copy link
Author

Reverse a String in Java is one of the most frequently asked java programs in the technical round of java fresher’s interview. There are different ways to reverse a string, using in-built methods, using recursion, etc.

If you wanted to know all the different methods on how can you reverse a string read this article on Scaler Topics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment