Reversing a string can be done in different ways. One approach is to create a new string by appending characters from the end of the original string. Another approach is to use StringBuilder or StringBuffer, which provide a built-in reverse() method. We use the @Test annotation to execute the reverseString method from the ReverseString class, which reverses a string using three different approaches. I have provided program demonstrating both of these approaches below.
Example Script:
import org.testng.annotations.Test;
public class ReverseString {
@Test
public void reverseString() {
String str=”Testing”;
System.out.println(“Reversed String from method1 for “+str+” is “+method1(str));
System.out.println(“Reversed String from method2 for “+str+” is “+method2(str));
System.out.println(“Reversed String from method3 for “+str+” is “+method3(str));
}
public String method1(String str) {
String reversedStr=””;
int len=str.length();
for(int i=len-1;i>=0;i–) {
reversedStr=reversedStr+str.charAt(i);
}
return reversedStr;
}
public String method2(String str) {
StringBuilder st=new StringBuilder();
return st.append(str).reverse().toString();
}
public String method3(String str) {
StringBuffer st=new StringBuffer();
return st.append(str).reverse().toString();
}
}
Detailed Explanation for Method1:
In method1, we create a variable len and assign it the length of the string. Using a for loop, we iterate from index len - 1 down to 0. During each iteration, we retrieve the character at the current index using the charAt(i) method and append it to the reversedStr variable, thereby constructing the reversed string.
Detailed Explanation for Method2:
In this method, we instantiate a StringBuilder, append the original string to it, and reverse the string using the reverse() method. Finally, we convert the result to a String using the toString() method and return it.
Detailed Explanation for Method3:
In this method, we instantiate a StringBuffer, append the original string to it, and reverse the string using the reverse() method. Finally, we convert the result to a String using the toString() method and return it.