user2954528
user2954528

Reputation: 3

Why does the "Array constants can only be used in initializers" when the array is defined out of the class where it was created

I set the String array in another class but when I try to set the value a certain way it will return "Array constants can only be used in initializers".

import java.util.Scanner;

class People {

    String[] names;
    int age;
    int height;

}

public class Class {
    public static void main(String args[]) {

        People person1 = new People();

        People person2 = new People();

        People person3 = new People();

        // I can set the values like this.

        person1.names[0] = "Joe";
        person1.names[2] = "!";
        person1.names[3] = "?";

        // But not like the more effective way.
        person2.names = {"Apple", "Banana"};

        person1.age = 13;
        person1.height = 164;

    }
}

Upvotes: 0

Views: 541

Answers (1)

Reimeus
Reimeus

Reputation: 159754

The following syntax is used to instantiate an array on a line other than the declaration line:

person2.names = new String[] {"Apple", "Banana"};

Upvotes: 2

Related Questions