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?

3
  • garbage(Java) producing garbage. That's called productive garbage. Commented Apr 30, 2016 at 4:23
  • Sorry. I'm just a newbie Commented Apr 30, 2016 at 4:36
  • There's no need to apologize, it's a valid question. Commented Aug 6, 2017 at 23:08

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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())

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.