In other page you can see to reverse the String if we can make a different copy of the reversed String & suggested way to do this task efficiently.
But what if you want to reverse the original String itself, then we have to edit the original String like it is shown in another article on this site. And how we can use that way to reverse the String is shown below -
import java.lang.reflect.Field;
public class StringReverse {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String str1 = "Nitin";
String str2 = "Nitin";
String sub = str2.substring(3);
System.out.println(str1 == str2);
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] chr = (char[])field.get(str1);
int len = chr.length;
for(int i = 0; i < len/2; i++) {
char temp = chr[i];
chr[i] = chr[len-i-1];
chr[len-i-1] = temp;
}
System.out.println(str1);
}
}
But what if you want to reverse the original String itself, then we have to edit the original String like it is shown in another article on this site. And how we can use that way to reverse the String is shown below -
import java.lang.reflect.Field;
public class StringReverse {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String str1 = "Nitin";
String str2 = "Nitin";
String sub = str2.substring(3);
System.out.println(str1 == str2);
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] chr = (char[])field.get(str1);
int len = chr.length;
for(int i = 0; i < len/2; i++) {
char temp = chr[i];
chr[i] = chr[len-i-1];
chr[len-i-1] = temp;
}
System.out.println(str1);
}
}