0
String[] months = {"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

System.out.println(Arrays.toString(months));

String[] months = new String[] {"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

System.out.println(Arrays.toString(months));

These two codes gave the same result. So I'm wondering which is an appropriate way to write.

3
  • 1
    @NicholasK Please don't add unrelated tags. It is completely irrelevant what type of Array OP uses here. Commented Nov 1, 2018 at 10:45
  • @Sir.Hedgehog This question is not about using new for strings. It's about using new for arrays. Commented Nov 1, 2018 at 11:53
  • @khelwood one applies to the other. he just needs to read it and think about it a bit Commented Nov 1, 2018 at 12:17

1 Answer 1

4
String[] arr = { "Alpha", "Beta" };

and

String[] arr = new String[] { "Alpha", "Beta" };

do exactly the same thing. The first is a shortcut which is allowed when you are declaring an array variable and initialising it in the same line.

However, in other cases, you must use new String[] to declare the type of the array you are creating.

String[] arr;
arr = { "Alpha", "Beta" }; // this will not compile
arr = new String[] { "Alpha", "Beta" }; // this will compile
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.