Monday, 17 July 2017

Java | Reverse a String without using String class function


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);
     }
}

8 comments:

  1. Thanks for a great answer. Couldn't find better than this anywhere else.

    ReplyDelete
    Replies
    1. For updates keep following: http://algorithmforum.blogspot.in/

      Delete
  2. Awesome. I have learnt a bit of Reflection API this way. Thanks!

    ReplyDelete
  3. This is amazing, I like it. Thanks. Also, if you are visit our website if you are looking for assistance with your nursing assignment:

    Nursing Assignment Help

    ReplyDelete
  4. Great post! Using reflection to reverse a string is a unique approach. Thanks for sharing!
    full stack course in chennai

    ReplyDelete
  5. 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!

    data science internship |
    python internship |
    artificial intelligence internship |
    java internship |
    cyber security internship

    ReplyDelete
  6. 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

Related Posts Plugin for WordPress, Blogger...