35

I want to convert a character array to a string object using the toString() method in java. Here is a snippet of the test code I used:

import java.util.Arrays;
class toString{
    public static void main(String[] args){
        char[] Array = {'a', 'b', 'c', 'd', 'e', 'f'};
        System.out.println(Array.toString());
        }
}

In principle, it should print abcdef, but it is printing random gibberish of the likes of [C@6e1408 or [C@e53108 each time the program executes. I don't need an alternative out of this but want to know why this is happening.

Raedwald
  • 40,290
  • 35
  • 127
  • 207
sidharth sharma
  • 2,497
  • 5
  • 19
  • 20

9 Answers9

38

To get a human-readable toString(), you must use Arrays.toString(), like this:

System.out.println(Arrays.toString(Array));

Java's toString() for an array is to print [, followed by a character representing the type of the array's elements (in your case C for char), followed by @ then the "identity hash code" of the array (think of it like you would a "memory address").

This sad state of affairs is generally considered as a "mistake" with java.

See this answer for a list of other "mistakes".

Community
  • 1
  • 1
Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • Thank you Bohemian. can you also tell me the meaning or the context of the gibberish that is being printed otherwise. – sidharth sharma Aug 14 '11 at 22:08
  • @sidharth: It's not "gibberish" - see my answer for where it comes from. – Jon Skeet Aug 14 '11 at 22:12
  • Just upvoted this, over a year later as a similar issue hit me and I found this post - really surprised ```toString()``` wasn't overridden for an object dealing with human readable characters! – Fergus In London Nov 04 '12 at 18:06
  • You didn't actually explain how to get "abcdef" as OP requested. – shmosel Nov 09 '17 at 23:59
  • @Bohemian or anyone, is there a reason why it can't be/hasn't been re-implemented as part of a language change? – anacron Mar 22 '18 at 16:04
  • It isn't a mistake. Java arrays are special classes with zero builtin methods beyond what's directly inherited from Object and a single special field which isn't even handled like ordinary fields. In order to have Array.toString() to print what you seem to expect it would need to be overloaded on the Array class which is a non-starter. – Shmuel Newmark Mar 25 '21 at 08:07
  • @ShmuelNewmark IMHO it is a mistake that the array class provides a sensible toString. There is nothing whatsoever stopping the array class from being given such an upgrade: Just call `Arrays.toString(this)`. – Bohemian Mar 25 '21 at 08:39
  • @Bohemian But there is no real Array class. It's all written in C to be directly handled by the JVM. You could still put the logic in there, but then you're overriding a method in secret without a clear class inheritance structure. Someone calling that method would have to dig a lot just to find the actual logic being invoked. – Shmuel Newmark Mar 25 '21 at 09:17
34

I don't know where you get the idea that "in principle" it should print "abcdef". Where is that documented?

Something like [C@6e1408 is certainly not random gibberish - it's the same way of constructing a string from an object as any other type that doesn't override toString() inherits - it's a representation of the type ([ indicating an array; C indicating the char primitive type) followed by the identity hash code in hex. See the documentation for Object.toString() for details. As it happens, arrays don't override toString.

If you want [a, b, c, d, e, f] you can use Arrays.toString(char[]). If you want abcdef you can use new String(char[]).

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • 1
    I think *'in principle'* it is expected to overwrite the ```toString()``` method as it deals with characters and human-readable content which could be outputted to a valid human-readable string. Or at the very least implement something like the ```Arrays``` class, as you point out. From the first sentence of the documentation (as I skimmed it) I only saw **Returns a String object representing this Character's value.** which I expected to mean it overrides ```toString()``` + outputs a String object with a length of one; a human readable representation. Obviously my bad for skimming; but still! – Fergus In London Nov 04 '12 at 18:04
  • 4
    @FergusMorrow: That's the documentation for `Character.toString`. This isn't a single `char`, it's an *array*. Basically, you should only rely on `toString` doing anything particularly useful for classes where it's been overridden, and it isn't overridden for arrays. That's certainly a shame, but the OP had no good reason to expect anything different "in principle" IMO. – Jon Skeet Nov 04 '12 at 20:53
  • Actually, it is the purpose of the hash to be _random_. – avidD Jun 29 '13 at 14:25
  • 1
    @avidD: No, the purpose of a hash isn't to be *random*. It's to be different between different objects, as far as possible. It doesn't matter whether it's unpredictable or not - that's not the point. – Jon Skeet Jun 29 '13 at 14:58
  • @JonSkeet has the correct answer. You should accept it as such. – Mark Oct 07 '16 at 15:18
2

Just use the following commands to get your abcdef array printed

    String a= new String(Array);

    System.out.println(a);

there you have it problem solved !! now regarding why is printing the other stuff i think those guys above put some useful links for that. Ok gotta go !!

jhkj
  • 21
  • 1
2

Arrays don't override toString. There's a static method: java.util.Arrays.toString that should solve your problem.

import java.util.Arrays;
class toString {
    public static void main(String[] args){
        char[] Array = {'a', 'b', 'c', 'd', 'e', 'f'};
        System.out.println(Arrays.toString(Array));
    }
}
Brigham
  • 13,690
  • 3
  • 34
  • 45
1

Because a char array is an array of primitives and toString() will give you it's default (which is a hash of the object). Some classes will implement toString() to do cooler things, but primitaves will not.

Jon7
  • 7,005
  • 2
  • 31
  • 39
0
char[] Array = { 'a', 'b', 'c', 'd', 'e', 'f' };
System.out.println(Array);

It should print abcdef.

Vinay Prajapati
  • 6,025
  • 4
  • 36
  • 75
Khanh Tran
  • 29
  • 5
  • This is correct but this doesn't quite fit the question. OP wants to convert the `char[]` to a `String`, and not just print it. He just used the print statement as a "debug"-option to show the output of `.toString()`. – Impulse The Fox Apr 26 '18 at 09:47
0

There is a spelling mistake of "Array.toString()" to "Arrays.toString(Array)" I guess so, and instead of writing name.toString(), pass the name as an argument and Write as above.

0

The default implementation of the toString method of the char [] class returns a String representation of the base address of the array, which is what is being printed here. We cannot change it, since the class of char [] is not extendable.

om-nom-nom
  • 60,231
  • 11
  • 174
  • 223
Swaranga Sarma
  • 12,215
  • 19
  • 54
  • 87
-3

this way I found worked:

public String convertToString(char[] array, int length)
{
String char_string;
String return_string="";
int i;

   for(i=0;i<length;i++)
   {
       char_string=Character.toString(array[i]);
       return_string=return_string.concat(char_string);
   }
   return return_string;
}