0

Why is the toString method returning jibberish?

char[] arrays = {'a','b','c'};
  { a, b, c }
arrays.toString()
  "[C@6519ceb1"
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
dukevin
  • 22,384
  • 36
  • 82
  • 111

2 Answers2

6

What you are seeing is the string representation of the array object as an Object. (The default behavior of toString() for all objects is to print a representation of the object reference. You cannot override that behavior for arrays.) To get a string representation of the contents of the array, you need to either pass the character array to a String constructor:

char[] arrays = {'a','b','c'};
String s = new String(arrays); // "abc"

or (depending on what you are trying to accomplish) use

String s = java.util.Arrays.toString(arrays); // "[a,b,c]"
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • +1, but shouldn't that be `array` rather than `arrays`? (Despite what OP might have coded?) – Bohemian Jan 17 '14 at 03:36
  • In that case,he's not getting a string (like a word) he's getting the string interpretation of an array, which doesn't seem like what he wants? –  Jan 17 '14 at 03:36
  • @Bohemian - OP's original code named the array `arrays`; I was just going with that. Personally, I would name such an array something less confusing (like `theArray` or `theChars`). – Ted Hopp Jan 17 '14 at 03:38
  • @developercorey - I don't know what OP wants, only that he doesn't want the default `toString()` behavior. (Incidentally, using `new String(arrays)` will produce exactly the same output as your code.) – Ted Hopp Jan 17 '14 at 03:38
  • @Bohemian are you referring to `java.util.Arrays.toString`? I believe it is `arrays` – Baby Jan 17 '14 at 03:42
  • @RafaEl no, the variable name `char[] arrays` is a stupid name - it's not many arrays, and *an* array, so the better name would be `char[] array`. – Bohemian Jan 17 '14 at 03:59
  • @Bohemian LOL you are definitely right. but some people doesn't really care about the naming – Baby Jan 17 '14 at 04:03
1
char[] arrays = {'a','b','c'};
System.out.println(Arrays.toString(arrays));

This is using java.util.Arrays Implementation can be found

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.toString%28java.lang.Object%5B%5D%29

By default it is using Object class's toString implementation

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
SSharma
  • 124
  • 1
  • 7