Question

Hi I'm writing a test program to reverse a string. When I convert the character array to a string using the toString() method, I get the wrong output. When I try to print the array manually using a for loop without converting it to a string the answer is correct. The code I've written is shown below:

import java.util.*;
public class stringManip {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String str = "This is a string";
    System.out.println("String=" +str);
    //reverse(s);

    char[] c = str.toCharArray();
    int left = 0;
    int right = str.length() - 1;
    for (int i = 0; i < (str.length())/2; i++)
    {
        char temp = c[left];
        c[left++] = c[right];
        c[right--] = temp;
    }
    System.out.print("Reverse="+c.toString());


    }
}

I should get the reverse of the string I entered, instead the output am getting is:

String=This is a string

Reverse=[C@45a1472d

Is there something am doing wrong when using the toString() method? Any help is appreciated. Thank you.

Était-ce utile?

La solution

Arrays don't override the toString() method. What you're seeing is thus the output of the default Object.toString() implementation, which contains the type of the object ([C means array of chars) followed by its hashCode.

To construct a String from a char array, use

new String(c)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top