How to Reverse a String in Java
In this blog, we will learn how to reverse a string in Java. This will be asked in the most of the interviews. This can be implemented in four different ways listed below:
- Convert String into Character Array and use For loop
- For loop with CharAt() method
- Using StringBuffer class
- Using StringBuilder class
Method 1:
Convert String into Character Array and use For loop
In the below snippet, we have done the following:
- Creating a new string and assigning a custom string value to it
- Converting this string to character array using toCharArray() method
- Calculating the length of character array and assigning it to a int variable.
- Using for loop, we will iterate this to print the string in reverse
public class StringReverseDemo { public static void main(String[] args) { String inputstring = "Krishna"; char[] chars = inputstring.toCharArray(); int length = chars.length; for (int i = length-1; i >=0; i--) { System.out.print(chars[i]); } } }
Method 2:
Convert String into Character Array and use For loop
In the below snippet, we have done the following:
- Creating a new string and assigning a custom string value to it
- Converting this string to character array using toCharArray() method
- Calculating the length of character array and assigning it to a int variable.
- Creating an another new string to concat the values to a brand new string
- Using charAt() method, we will iterate this for loop to print the string in reverse and concat it to the newly created string
public class StringReverseDemo { public static void main(String[] args) { String inputstring = "Krishna"; String revword = ""; char[] chars = inputstring.toCharArray(); int length = chars.length; for (int i = length-1; i >=0; i--) { revword = revword+inputstring.charAt(i); } System.out.println(revword); } }
Method 3:
Using StringBuffer class
We can use StringBuffer class to reverse a string value with help of its inbuilt methods directly as below:
public class StringReverseDemo { public static void main(String[] args) { String inputstring = "Krishna"; StringBuffer stringbuffer = new StringBuffer(inputstring); System.out.println(stringbuffer.reverse()); } }
Method 4:
Using StringBuilder class
We can use StringBuilder class to reverse a string value with help of its inbuilt methods directly as below:
public class StringReverseDemo { public static void main(String[] args) { String inputstring = "Krishna"; StringBuilder stringbuilder = new StringBuilder(inputstring); System.out.println(stringbuilder.reverse()); } }
Please watch the Youtube video for better understanding.