Thursday, September 4, 2014

Convert String to Character Array without calling toCharArray method

One post from LinkedIn came into my sight questioning that how to compare two String objects without using any inbuilt methods of this class. The solution iss trivial, comparing the lengths and every characters of the given strings, but to convert the String into char[] one need to call toCharArray() method and which is not permissible for the OP.
So to solve this problem I came up with a solution which I would like to share with you. String class stores the characters internally within a field called value and the signature of this field is:
private final char value[];
My intention is to deal with this field directly and for this type of cases Java Reflection comes very handy. So I wrote the following code which might come helpful for me in future or for you.
@SuppressWarnings({ "rawtypes", "unchecked" })
public static char[] toCharArray(String str) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
 final Field field = String.class.getDeclaredField("value");
 AccessController.doPrivileged(new PrivilegedAction() {

  public Object run() {
   return null;
 Object obj = field.get(str);
 char[] charArr = char[].class.cast(obj);
 return charArr;
Hope it will help.

No comments:

Post a Comment