0

Having trouble declaring and then initialising an array of strings in java. Was confused as to why it was happening so copied a peice of example code from Grails Cookbook and that doesnt seem to work either?

public class StringArray{
    String[] testArray = new String[5];
    
testArray[0] = "Daddy";
testArray[1] = "Mommy";
testArray[2] = "Brother";
testArray[3] = "Sister";
testArray[4] = "Dog";
}

sample of error messages

C:\Users\aejmu\Desktop\MSc_CIS\javaLabs>javac StringArray.java
StringArray.java:5: error: ']' expected
testArray[0] = "Daddy";
          ^

included a screenshot of the code in sublime. Im sure there's an obvious reason for this but i cant for the life me figure it out.

  • Does this answer your question? [How do I declare and initialize an array in Java?](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) – wovano Aug 11 '20 at 17:20
  • 1
    You can't have assignments like that outside of a method, constructor or (static) initializer. – Mark Rotteveel Aug 12 '20 at 07:22

2 Answers2

3

The statements that initialize the array need to be placed in the body of a method or constructor. The example you took probably assumes the entire code is within a method.

The one-line initialization way still works in your case:

public class StringArray{
    String[] testArray = {"Daddy", "Mommy", "Brother", "Sister", "Dog"};
}
M A
  • 65,721
  • 13
  • 123
  • 159
-1

Include public static void main(String[] args){//code} following the class header. Here is an example:

Code

The output: Daddy, Mommy, Brother, Sister, Dog,

blin
  • 1
  • 2
  • 1
    Welcome to Stackoverflow. Please edit your answer and post your code instead of linking to a picture (links can get unavailable and the code is not copy/past), thanks. – Michael Fehr Aug 11 '20 at 18:12