Why does the toString method in java not seem to work for an array

38,174

Solution 1

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".

Solution 2

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[]).

Solution 3

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

Solution 4

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 !!

Solution 5

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.

Share:
38,174
sidharth sharma
Author by

sidharth sharma

I am a computer science student and an open-source enthusiast. I base all my projects and technical activities exclusively on Linux. I experiment with stuff, particularity related to new technologies. I like to learn everything and for that I am open to seeking help and eager to offer it as well.

Updated on July 20, 2020

Comments

  • sidharth sharma
    sidharth sharma almost 4 years

    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.

  • BoltClock
    BoltClock over 12 years
    "a char array is a primitive" You mean an array of primitives, surely.
  • sidharth sharma
    sidharth sharma over 12 years
    Thank you Bohemian. can you also tell me the meaning or the context of the gibberish that is being printed otherwise.
  • Jon Skeet
    Jon Skeet over 12 years
    @sidharth: It's not "gibberish" - see my answer for where it comes from.
  • colithium
    colithium about 12 years
    He is not asking for an alternative, he is asking for an explanation of the behavior.
  • Fergus In London
    Fergus In London over 11 years
    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
    Fergus In London over 11 years
    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!
  • Jon Skeet
    Jon Skeet over 11 years
    @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.
  • avidD
    avidD almost 11 years
    Actually, it is the purpose of the hash to be random.
  • Jon Skeet
    Jon Skeet almost 11 years
    @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.
  • Mark
    Mark over 7 years
    @JonSkeet has the correct answer. You should accept it as such.
  • shmosel
    shmosel over 6 years
    You didn't actually explain how to get "abcdef" as OP requested.
  • anacron
    anacron about 6 years
    @Bohemian or anyone, is there a reason why it can't be/hasn't been re-implemented as part of a language change?
  • Impulse The Fox
    Impulse The Fox about 6 years
    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().
  • Shmuel Newmark
    Shmuel Newmark about 3 years
    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.
  • Bohemian
    Bohemian about 3 years
    @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).
  • Shmuel Newmark
    Shmuel Newmark about 3 years
    @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.