package com.java.tricks;
import java.lang.reflect.Field;
public class ReverseString {
/**
* This method is used to reverse string without using any string class method.
*/
private static void reverseString(String value) {
try {
/** to access the private value[] array of String class. */
Field field = String.class.getDeclaredField("value");
/** Grant the access to access the field value. */
field.setAccessible(true);
/** Access the value array from the String class. */
char[] array = (char[]) field.get(value);
int i = 0; int j = array.length-1;
/** Reverse the array values to reverse it. */
while(i<j) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
i++; j--;
}
/** Set the reversed array into the String Object. */
field.set(value, array);
} catch (NoSuchFieldException | SecurityException |
IllegalArgumentException | IllegalAccessException e) {
System.err.println(e.getCause());
}
}
/**
* Driver method to reverse a String.
*/
public static void main(String[] args) {
String value = "geeksforgeeks";
System.out.println(value);
reverseString(value);
System.out.println(value);
}
}
Thanks for a great answer. Couldn't find better than this anywhere else.
ReplyDeleteFor updates keep following: http://algorithmforum.blogspot.in/
DeleteNice Explanation given
ReplyDeleteAwesome. I have learnt a bit of Reflection API this way. Thanks!
ReplyDeleteThis is amazing, I like it. Thanks. Also, if you are visit our website if you are looking for assistance with your nursing assignment:
ReplyDeleteNursing Assignment Help
Great post! Using reflection to reverse a string is a unique approach. Thanks for sharing!
ReplyDeletefull stack course in chennai
Great trick for reversing a string without using String class methods! Clever use of reflection to manipulate the underlying character array. Thanks for sharing this innovative solution!
ReplyDeletedata science internship |
python internship |
artificial intelligence internship |
java internship |
cyber security internship
Great article! Very helpful for readers looking for clear insights. For those interested in skill development, check out best training institute in Chennai offering quality courses. Helpful information about best guest posting sites.
ReplyDelete