Deersfeet Deersfeet - 2 years ago 103
Java Question

String literal with toCharArray() producing garbage in Java

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:


What am I doing wrong?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download