1public class ReverseString {
2 public static void main(String[] args) {
3 String s1 = "neelendra";
4 for(int i=s1.length()-1;i>=0;i--)
5 {
6 System.out.print(s1.charAt(i));
7 }
8 }
9}
1// Library approach
2public static String solution(String str) {
3 // StringBuilder is not thread-safe, use StringBuffer
4 return new StringBuffer(str).reverse().toString();
5}
6
7// DIY approach
8public static String solution(String str) {
9 char[] chars = str.toCharArray();
10 for(int i = 0, j = str.length() - 1; i < j; i++, j--) {
11 char ch = chars[i];
12 chars[i] = chars[j];
13 chars[j] = ch;
14 }
15 return new String(chars);
16}
1String str = "Hello";
2String reverse(String str){
3 StringBuilder sb = new StringBuilder();
4 sb.append(str);
5 sb.reverse();
6 return sb.toString();
7}
1String str = "Reverse this strings";
2//for loop
3for (int i = str.length() - 1; i >= 0; i--) {
4 System.out.print(str.charAt(i));
5}
6
7// StringBuffer for multi thread
8StringBuffer sb = new StringBuffer();
9sb.append(str);
10System.out.print(sb.reverse().toString());
11
12// StringBuffer for single thread
13StringBuilder sb = new StringBuilder();
14sb.append(str);
15System.out.print(sb.reverse().toString());
1// reverse a string using character array
2class ReverseUsingCharacterArray
3{
4 public static void main(String[] args)
5 {
6 String str = "HelloWorldJava";
7 char[] ch = str.toCharArray();
8 for(int a = ch.length - 1; a >= 0; a--)
9 System.out.print(ch[a]);
10 }
11}