1
String s = new String({'h','e','l','l','o'});

I received the error:

1 Invalid expression term '{'

I thought {'h','e','l','l','o'} should be a character array, why did it fail to compile?

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Adam Lee
  • 24,710
  • 51
  • 156
  • 236
  • See http://stackoverflow.com/a/5678393/414076 and Section 7.6.10.4 of the language specification. Your specific example is only a legal array initialization syntax in conjunction with a variable declaration, which is notably missing in your code. – Anthony Pegram Jun 28 '12 at 01:13

2 Answers2

6

I think you mean:

String s = new String(new[] {'h','e','l','l','o'});

The code you had before was not initializing an array correctly. Check out the MSDN article on implicitly typed arrays for more info.

You could also explicitly specify the type of the array:

String s = new String(new char[] {'h','e','l','l','o'});
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
3

Try something like this:

String s = new String(new char [] {'h','e','l','l','o'});
anttix
  • 7,709
  • 1
  • 24
  • 25