1

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?

2
  • 1
    You need to initilize the array Commented Apr 8, 2013 at 6:24
  • "it has an error." Copy/paste the error text as an edit to the question & use code formatting. Commented Apr 8, 2013 at 6:28

2 Answers 2

8

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.