-1

Working on a problem to reverse a string and I am getting [C@659e0bfd when I try to use the following method to reverse a string. Anyone know what's wrong with this code?

    public static String reverseString(String string) {
    if ((string == null) || (string.length() <= 1)){
        return string;
    }
    char[] charArray = string.toCharArray();
    char[] newString = new char[charArray.length];

    for (int i = 0; i < charArray.length; i++ ){
        newString[i] = charArray[(charArray.length -1)-i];
        }       
    return newString.toString();
}
user3871995
  • 983
  • 1
  • 10
  • 19
  • I voted to close this question for being off-topic. You should try at least to explain your code idea, what you expect as result and the error you are getting. – luksch Jul 18 '15 at 13:54
  • @Codebender agreed. I may have been a bit overreacting. – luksch Jul 18 '15 at 14:07

3 Answers3

2

you are returning array.toString(). if you want to know why it gives C@659e0bfd read this question.

to fix this you can use

return new String(newString);//create string from adding all chars together

public String(char[] chars) is a overloaded constructor of String class which create a new String with array of character

Community
  • 1
  • 1
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
1

A char[]'s toString() method is not overridden. Which means, it will give back the value provided by Object.toString() method.

You should instead use return new String(newString)

Codebender
  • 14,221
  • 7
  • 48
  • 85
0

Firstly, all your code, except first if clause can be replaced by only one string:

return new StringBuilder(string).reverse().toString();

Secondly, you don't need nested parentheses in your if clause. So, the method will be the following:

public static String reverseString(String string) {
        if (string == null || string.length() <= 1){
            return string;
        }
        return new StringBuilder(string).reverse().toString();
    }
VeLKerr
  • 2,995
  • 3
  • 24
  • 47