0

I wanted to create a char array of the alphabet. I looked at this post:

Better way to generate array of all letters in the alphabet

which said this:

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();

So in my code I have:

public class Alphabet {

private char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

public String availableLetters(){

    return letters.toString();
   } 

}

When I call the function availableLetters() from main() and printit to the console, it outputs this garbage:

[C@15db9742

What am I doing wrong?

Community
  • 1
  • 1
Deersfeet
  • 61
  • 1
  • 10

3 Answers3

5

The array is correct, the problem is that you are not printing it correctly.

If you print your array one character at a time, you would get a correct result:

for (char c : letters) {
    System.out.print("'" + c + "' ");
}

demo

Unfortunately, Java standard class library does not provide a meaningful override of toString() for arrays, causing a lot of trouble for programmers who are new to the language.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

If you want to print it in array form, then use:

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

BTW: The [C@15db9742 is not really garbage. It's what gets printed out when a class does not override the toString() method.

From Object.toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
-1

You can pass the char array to the String constructor or the static method String.valueOf() and return that instead.

klog
  • 486
  • 3
  • 10