-2

Possible Duplicate:
Simplest way to print an array in Java

public char[] createArray() {        
  char[] s;        
  s = new char[26];

  for ( int i=0; i<26; i++ ) {    
    s[i] = (char) (’A’ + i);   
  }            
  return s;

  // how to print s?

  }
Community
  • 1
  • 1

2 Answers2

5

If you want to print is as an array

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

if you want to print as a String

System.out.println(new String(s));

btw you can write

char[] s = new char['Z' - 'A' + 1];
for(char ch = 'A'; ch <= 'Z'; ch++)
   s[ch - 'A'] = ch;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thanks, could you also let me know what is the meaning of very first line.. Thanks. – user1947627 Jan 04 '13 at 12:19
  • From the Javadoc `Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(char). Returns "null" if a is null.` – Peter Lawrey Jan 04 '13 at 12:21
2

You can just use Arrays.toString(s) and print the resulting String.

amit
  • 175,853
  • 27
  • 231
  • 333