Pages

How to reverse a string in java ?

How to reverse a string in java ?

>> In Java we can reverse a string using for loop, string buffer, string builder,....

public class reverse {
public static void main(String[] args) {

String str = "WELCOME";

char[] carray = str.toCharArray();
String rev = "";

for (int i = 0; i <= carray.length - 1; i++) {
rev = rev + str.charAt(carray.length - i - 1);
}
System.out.println(
"reverse string using for loop=" + rev);
String reve = "";
for (int i = carray.length - 1; i >= 0; i--) {
reve = reve + str.charAt(i);
}

System.out.println(
"<<------------------------------------------>>");
System.out.println(
"reverse string using for loop=" + reve);

System.out.println(
"<<------------------------------------------>>");
StringBuilder sb = new StringBuilder(str);
System.out.println("reverse string using StringBuilder reverse method=" + sb.reverse());


System.out.println(
"<<------------------------------------------>>");
StringBuffer sber = new StringBuffer(str);
System.out.println("reverse string using StringBuffer reverse method=" + sber.reverse());

}
}
Output:
java reverse a string

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.