I'm trying to create a string array, but the compiler keeps giving me an error message on the lines I assign a value to each index of the array. Here's the code:

String[] greeting = new String[4];
	greeting[0] = "Why, Hello there!";
	greeting[1] = "Welcome.";
	greeting[2] = "blah blah blah";
	greeting[3] = "more useless crap";

The error messages I get are: ']' expected, ';' expected, illegal start of type, and <identifier> expected. I know creating an array is pretty basic, but I can't figure out what I'm doing wrong. Any help would be appreciated.

Recommended Answers

All 7 Replies

This certainly should work, there's no errors I can find and it compiles okay here.

"Illegal start of type" suggests that there may be a problem in the boilerplate. Check to see that you have the closing square bracket on your main() declaration:

public static void main(String args[])
//                                  ^ is this there?

The bracket on my main declaration is there. Any other suggestions? If you need to the the entire source code
, let me know.

Yeah, since I can't see anything wrong here, let's see the rest of it.

Okay, I attached the .java file.

Thanks. I've got to run out, but I'll try to look at it tonight.

You have incorrectly placed these lines of code outside of methods. This means that you are declaring attributes for your class. When you declare an array, you may initiate the String array with the corresponding values at the same time. However you wrote assignments' code during declaration, which is wrong.
String[] greeting = new String[4]; // declare an attribute of STring array. It's good.
greeting[0] = "Why, Hello there!"; // Wrong. Assignment shoud be written within a method.
greeting[1] = "Welcome.";//wrong
greeting[2] = "blah blah blah";// wrong
greeting[3] = "more useless crap";// wrong

You may write one line of code to complete the task.

String[] greeting = {"Why, Hello there!","Welcome.","blah blah blah","more useless crap"};

Okay, thanks for the help, I knew I could do it like that, I just didn't want to. I guess I have to.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.