Java is one of the most widely used programming languages in the world and hence a lot of questions are asked in interview from Java.
In this article, you will learn simple but most commonly asked Java Interview Question- How to reverse a string.
You will learn three method to reverse a string.
/*
There is an API for reversing a string in Java. StringBuffer and StringBuilder provides reverse()
method to reverse a string.
*/
package programs;
public class ReverseString {
public static void main(String[] args) {
/*************************method 1- Manual Method********************/
String str = "India";
String revStr = "";
//Convert String to char array
char[] strArray = str.toCharArray();
//find length of char array
int len = strArray.length;
//iterate over char array from last index to first index
for (int i = len - 1; i >= 0; i--) {
revStr = revStr + str.charAt(i);
}
System.out.println("Method 1 : Manually reversing a string");
System.out.println(revStr);
/*************************method 2 - Using StringBuffer********************/
StringBuffer sbf=new StringBuffer(str);
System.out.println("Method 2 : Reverse string using StringBuffer");
System.out.println(sbf.reverse());
/*************************method 3 - Using StringBuilder********************/
StringBuilder sbl=new StringBuilder(str);
System.out.println("Method 3 : Reverse string using StringBuilder");
System.out.println(sbl.reverse());
}
}
In this article, you will learn simple but most commonly asked Java Interview Question- How to reverse a string.
You will learn three method to reverse a string.
/*
There is an API for reversing a string in Java. StringBuffer and StringBuilder provides reverse()
method to reverse a string.
*/
package programs;
public class ReverseString {
public static void main(String[] args) {
/*************************method 1- Manual Method********************/
String str = "India";
String revStr = "";
//Convert String to char array
char[] strArray = str.toCharArray();
//find length of char array
int len = strArray.length;
//iterate over char array from last index to first index
for (int i = len - 1; i >= 0; i--) {
revStr = revStr + str.charAt(i);
}
System.out.println("Method 1 : Manually reversing a string");
System.out.println(revStr);
/*************************method 2 - Using StringBuffer********************/
StringBuffer sbf=new StringBuffer(str);
System.out.println("Method 2 : Reverse string using StringBuffer");
System.out.println(sbf.reverse());
/*************************method 3 - Using StringBuilder********************/
StringBuilder sbl=new StringBuilder(str);
System.out.println("Method 3 : Reverse string using StringBuilder");
System.out.println(sbl.reverse());
}
}
Output:
Method 1 : Manually reversing a string
aidnI
Method 2 : Reverse string using StringBuffer
aidnI
Method 3 : Reverse string using StringBuilder
aidnI