Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Array Assignment in Java [duplicate]

Code:

String Foo[];
Foo={"foo","Foo"};

Error at Line 2: Illegal Start of expression
The code works if I say:

String Foo[]={"foo","Foo"};

Why does this happen, and how should I do the required without generating an error? This also happens with other data types.

Would appreciate if you could explain in layman terms.

like image 244
Stephen Allen Avatar asked Mar 31 '26 16:03

Stephen Allen


1 Answers

{"foo","Foo"} is an array initializer and it isn't a complete array creation expression:

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

Java Specification

Use new String[] {"foo","Foo"} instead.

like image 162
Andrew Tobilko Avatar answered Apr 02 '26 04:04

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!