Last active
March 7, 2022 10:45
-
-
Save bikashdaga/8f9006cf56d824a5fbadd4ed25a0fcf1 to your computer and use it in GitHub Desktop.
How to Reverse a String in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.