-4

I wanted to add an array as an instance field, also a part of an object, however it gives me interesting errors when i try to do so:

class Surgeon {
  private String[] surgeons;

  public Surgeon() {
    this.surgeons = {"Romero", "Jackson", "Hannah", "Camilla"};
  }

  public static void main(String[] args) {
    Surgeon surg = new Surgeon();
  }
}

And it gives me three errors.

This does not make any sense bc is it not how you initialize an array?

  • 6
    "*And it gives me three errors.*" - Please [edit] the post and include the errors. – Turing85 Mar 17 '22 at 22:59
  • 2
    The correct syntax is: `this.surgeons = new String[] {"Romero", "Jackson", "Hannah", "Camilla"};` – Turing85 Mar 17 '22 at 23:02
  • 2
    I am curious as to what the other two errors were (since there was only one in the posted code). – hfontanez Mar 17 '22 at 23:06
  • @hfontanez I use `Eclipse` and got one error and one warning (`surg` not used). I would imagine it depends on the ide and the error settings. – WJS Mar 17 '22 at 23:17
  • @WJS Elclipse is a very hard IDE to use in my opinion, i rather use IntelliJ IDEA – mohammedabergsson581 Mar 17 '22 at 23:28
  • @WJS But you and I know warnings are not errors. That's why I am curious about what the other two "errors" were. My guess is that the OP had more broken code in the same project that had nothing to do with this particular issue. – hfontanez Mar 17 '22 at 23:40
  • @hfontanez That's why I mentioned the ide and settings. I can set some warnings to be errors if I want. Or just ignore them completely. – WJS Mar 17 '22 at 23:50
  • Does this answer your question? [Arrays constants can only be used in initializers error](https://stackoverflow.com/questions/6348479/arrays-constants-can-only-be-used-in-initializers-error) – Med Elgarnaoui Mar 18 '22 at 00:06
  • Please review https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java – Eugene Mar 18 '22 at 00:15

1 Answers1

1

You have to add the operator "new" to instantiate the array in the class constructor

public Surgeon() {
this.surgeons = new String[]{"Romero", "Jackson", "Hannah", "Camilla"};
}
averageDev
  • 26
  • 1