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.

khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

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
khelwood
  • 55,782
  • 14
  • 81
  • 108