jkl
jkl

Reputation: 675

Why can't i construct string array like this in Java?

I am trying to initialize a string array like below but it has an error.

public class Account{
    private String[] account;

    public Account()
    {
        account = {"A", "B", "C"};
    }
}

Does anyone knows why it keep creating an error?

Upvotes: 1

Views: 143

Answers (2)

NPE
NPE

Reputation: 500167

The correct syntax to use inside the constructor is

account = new String[]{"A", "B", "C"};

The shortcut syntax you are trying to use is only permitted at the point of declaration:

private String[] account = {"A", "B", "C"};

As to why the distinction, see Why can array constants only be used in initializers?

Upvotes: 8

prashant
prashant

Reputation: 1815

Refer: Arrays constants can only be used in initializers error

Also Refer: Why can array constants only be used in initializers?

"If you want to use the array initializer, you cannot split the declaration and assignment."

Upvotes: 0

Related Questions